Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install hf-cloud-sagemaker-production-defaults@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin hf-cloud-sagemaker-production-defaults v1.0.0 follows the Agent Plugins spec.
gh skills-hub install hf-cloud-sagemaker-production-defaults Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/hf-cloud-sagemaker-production-defaults/ Extract the ZIP to .github/skills/ in your repo. The folder name must match hf-cloud-sagemaker-production-defaults for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 26.8 KB
---
name: hf-cloud-sagemaker-production-defaults
description: 'Create a SageMaker endpoint (real-time, real-time scale-to-zero, 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, deploy_ic.py for real-time endpoints that scale to zero instances via inference components, and deploy_async.py for async endpoints (also scale-to-zero). 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.'
---
# 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:
1. **SageMaker Model** — image + env vars + execution role + S3 artifacts
2. **Endpoint config** — instance type, initial count, optional data capture
3. **Endpoint** — the real-time endpoint serving inference
4. **Autoscaling target + policy** — target tracking on invocations per instance
5. **CloudWatch alarms** — latency, errors, platform overhead
An inference-component deployment (`deploy_ic.py`) creates the same set with two changes: the endpoint config carries the execution role and `ManagedInstanceScaling`, and an **inference component** carries the model. Its autoscaling target is the component, not the variant.
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-capture`.
All resources get a consistent tag set including `CreatedBy=agentic-deploy-skills` for later cleanup.
Defaults and reasoning in `references/deployment-template.md`.
## Running the deployment
For a text-generation LLM (vLLM), first package the pinned model snapshot as a SageMaker `model.tar.gz` artifact and upload it to an account-controlled S3 bucket. SageMaker extracts it under `/opt/ml/model`, so the deployment does not fetch or execute repository code at runtime:
```bash
python scripts/deploy.py \
--model-name qwen3-medical \
--image-uri "$IMAGE_URI" \
--inference-ami-version "$AMI" \
--role-arn "$ROLE_ARN" \
--model-s3-uri "s3://<your-model-bucket>/qwen3-medical/model.tar.gz" \
--instance-type ml.g5.xlarge \
--region "$REGION" \
--env SM_VLLM_MODEL=/opt/ml/model \
--env SM_VLLM_HOST=0.0.0.0 \
--env SM_VLLM_TRUST_REMOTE_CODE=false \
--env SM_VLLM_MAX_MODEL_LEN=4096
```
For 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.5
```
Note: TEI deployments **do not** need `--inference-ami-version`. That flag is vLLM-specific. TEI env vars are also simpler (`HF_MODEL_ID` instead of `SM_VLLM_*`, no host or trust-remote-code to configure).
Where each value comes from:
| Parameter | Source |
|---|---|
| `--image-uri` | `hf-cloud-serving-image-selection` — agent reads from the AWS DLC catalog page |
| `--inference-ami-version` | `hf-cloud-serving-image-selection` — required for vLLM tags containing cu130+ |
| `--role-arn` | `hf-cloud-sagemaker-iam-preflight` (`check_role.py`) |
| `--region` | `hf-cloud-aws-context-discovery` |
| `--instance-type` | User input or planner recommendation |
| `--env` | Model-specific; see `hf-cloud-serving-image-selection` for required `SM_VLLM_*` vars |
| `--model-s3-uri` | Preferred for production — S3 URI of the pinned model artifact extracted to `/opt/ml/model`; omit only for the Hub-at-runtime exception |
The script creates resources in order with error handling, waits for `InService` (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.
The scripts ship with this skill. If the installed copy is missing the `scripts/` directory (some harnesses copy only SKILL.md on install), fetch them from the source repo rather than re-implementing them from this description.
**Model-loading default**: pre-stage pinned weights in S3 and pass `--model-s3-uri`; the container loads them from `/opt/ml/model` without a runtime Hub dependency. Loading from the Hub is an explicit exception: expect a 5–15+ minute download after endpoint startup, provide a token for gated models, and keep `SM_VLLM_TRUST_REMOTE_CODE=false` unless the specific architecture requires reviewed custom code. `deploy.py` waits 30 minutes.
## InService is not success — smoke-test before declaring victory
`InService` only means the container answered `/ping`. In MMS-based containers (HF Inference Toolkit) the Java front-end answers pings even while the Python worker crash-loops — an endpoint can be InService and serve nothing. Two checks, always:
1. **One real invocation.**
- Real-time: `invoke_endpoint.py` (below) with a minimal payload; require an HTTP 200 with a sane body.
- Async: upload one input to S3, call `invoke-endpoint-async`, 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.
2. **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
```
Inference-component deployments log to `/aws/sagemaker/InferenceComponents/<component-name>` instead. `deploy_ic.py` scans that group automatically while it waits.
**General rule for denied diagnostics**: when a read-only call the workflow uses for diagnosis is denied (a restricted role without `logs:FilterLogEvents`, `servicequotas:ListServiceQuotas`, and so on), say so in one line and carry on with the checks that do work. Never block a deployment on a permission needed only for diagnosis, and never read a denied call as evidence that nothing is wrong.
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 `InService`, test it with the bundled helper. It is cross-platform and **BOM-safe** — use it instead of hand-writing a payload file and calling `invoke-endpoint` directly:
```bash
# 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 $REGION
```
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.
### The UTF-8 BOM gotcha (Windows)
If you write the request payload yourself on Windows, **do not** use `Set-Content -Encoding UTF8` — depending on the PowerShell version it prepends a UTF-8 byte-order mark (BOM). SageMaker's JSON parser rejects a BOM with a 400 `ModelError`:
```
Unexpected 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. `invoke_endpoint.py` avoids it entirely (it even strips a BOM from a `--payload-file` that already has one). If you must call the CLI directly, write the body as BOM-free UTF-8:
```powershell
# 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.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.
### Invoking a generative reranker (vLLM)
Generative rerankers (Qwen3-Reranker etc. — routed to the HuggingFace vLLM DLC by `hf-cloud-serving-image-selection`) are causal LMs scored by their first generated token, not chat models. Use the **completions API with a raw `prompt`**, not the messages/chat API: chat templating does not reliably honor `chat_template_kwargs` such as `{"enable_thinking": false}`, and a wrong template silently returns near-identical scores for every query–document pair instead of erroring.
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 `<|im_start|>assistant\n<think>\n\n</think>\n\n` 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: `P("yes") / (P("yes") + P("no"))`. 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.
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](https://aws.github.io/deep-learning-containers/reference/available_images/) — pick the row that matches the model family (HuggingFace vLLM for LLMs, TEI for embeddings, etc.), substitute `<region>` with the deployment region, and pass to `deploy.py --image-uri`.
For vLLM images specifically (both `huggingface-vllm` and the AWS `vllm` fallback), also check the tag's CUDA version:
```bash
# 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 `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.
## Scale to zero for real-time endpoints
A real-time endpoint reaches zero instances only when it hosts **inference components**. The variant-scoped target that `deploy.py` registers cannot go below one instance. `deploy_ic.py` builds the component-based shape instead.
Use it when traffic is sparse or scheduled, and the client tolerates a multi-minute first request. Do not use it for interactive traffic with an SLA: the wake takes minutes, and every request during the wake fails.
```bash
python scripts/deploy_ic.py \
--model-name qwen3-scale-to-zero \
--image-uri "$IMAGE_URI" \
--inference-ami-version "$AMI" \
--role-arn "$ROLE_ARN" \
--model-s3-uri "s3://<your-model-bucket>/qwen3-scale-to-zero/model.tar.gz" \
--instance-type ml.g5.xlarge \
--region "$REGION" \
--env SM_VLLM_MODEL=/opt/ml/model \
--env SM_VLLM_HOST=0.0.0.0 \
--env SM_VLLM_TRUST_REMOTE_CODE=false \
--env SM_VLLM_MAX_MODEL_LEN=4096
```
### How it differs from deploy.py
| Piece | Model-based (`deploy.py`) | Component-based (`deploy_ic.py`) |
|---|---|---|
| Execution role | on the Model | on the **endpoint config** (`ExecutionRoleArn`) |
| Model reference | `ProductionVariants[].ModelName` | `InferenceComponent.Specification.ModelName`; the variant has no `ModelName` |
| Instance floor | `InitialInstanceCount`, min 1 | `ManagedInstanceScaling {Status: ENABLED, MinInstanceCount: 0}` |
| Scaling target | `endpoint/<ep>/variant/AllTraffic`, `sagemaker:variant:DesiredInstanceCount` | `inference-component/<ic>`, `sagemaker:inference-component:DesiredCopyCount` |
| Scaling metric | `SageMakerVariantInvocationsPerInstance` (20/min) | `SageMakerInferenceComponentConcurrentRequestsPerCopyHighResolution` (5 concurrent/copy) |
| Wake from zero | not applicable | step policy + `NoCapacityInvocationFailures` alarm |
| Invocation | endpoint name | endpoint name **plus** `InferenceComponentName` |
`InferenceAmiVersion` still belongs on the variant, and it coexists with `ManagedInstanceScaling` (verified on `cu130` + `ml.g5.xlarge`).
Four pieces make zero work, and all four are required. Target tracking cannot leave zero, because it cannot divide by zero copies. Drop the step policy or its alarm and the endpoint scales to zero once, then never answers again. `deploy_ic.py` wires all four.
### Measured behaviour
`Qwen/Qwen3-0.6B` from the Hub, `ml.g5.xlarge`, `us-east-1`, July 2026:
| Step | Time |
|---|---|
| Endpoint `InService` (it starts empty, no model loads) | 4 min |
| Component `InService` (Hub download + vLLM boot + CUDA graphs) | +6 min |
| Idle to 0 copies | 11 min after the last request |
| 0 copies to 0 instances | +12 min |
| First request at zero → HTTP 400 `has no capacity` | immediate |
| `NoCapacityInvocationFailures` alarm → ALARM | +67 s |
| Step policy raises desired copies and instances to 1 | +1 min 42 s |
| HTTP 200 | **+9 min 24 s** |
Scale-in is not tunable through this skill: Application Auto Scaling creates the AlarmLow itself with a 10 s period and 90 evaluation periods, so 15 minutes of idle datapoints are required before it fires.
Pre-stage production weights and pass `--model-s3-uri`. Besides avoiding runtime Hub access, this shortens every wake: model artifacts are loaded again on **every** wake, so their retrieval sits on the critical path of the first request after each idle period.
### Sizing the component
`ComputeResourceRequirements` is a scheduling reservation, not a cap. A component that requests 1024 MB runs vLLM with several GB of host memory without trouble.
The schedulable pool is far smaller than the instance memory. On `ml.g5.xlarge` (16 GiB) the scheduler **accepts 1024 MB and rejects 4096 MB**. Over-asking gives an instant, confusing failure:
```
There is not enough hardware resources on the instances for this endpoint to
create a copy of the inference component.
```
That message appears even when the endpoint has a healthy instance. Treat it as "the request is too large", not "add instances". Start at the 1024 MB default and raise it only when several components share one instance.
`--accelerator-devices` must match `SM_VLLM_TENSOR_PARALLEL_SIZE` for multi-GPU models.
### Invoking and testing
Pass the component name, and allow for the wake:
```bash
python3 scripts/invoke_endpoint.py \
--endpoint-name <endpoint-name> \
--inference-component-name <component-name> \
--payload '{"prompt": "hello", "max_tokens": 16}' \
--wait-for-capacity 900 --region "$REGION"
```
The 400 `has no capacity` error is the wake signal, not a fault: it publishes the metric that triggers the step policy. With `--wait-for-capacity` the helper retries every 30 s until a copy serves the request. Without it, a cold endpoint always looks broken.
### Teardown order
`teardown.py` handles both shapes, but the order is load-bearing:
1. alarms (`<endpoint>-*` and `<component>-*`)
2. scaling policies and the scalable target, on the component resource id
3. **inference components**
4. endpoint, endpoint config, model
Two behaviours make this necessary:
- **`delete-endpoint` does not delete the components.** They survive, keep reporting `InService`, and block a new component with the same name. Always delete components first.
- **Component deletion is refused during transient states** — `CREATE_IN_PROGRESS` while the container boots, and `UPDATE_RC_IN_PROGRESS` while a scaling action changes the copy count. The script retries every 15 s for 15 min; a teardown right after a scaling event legitimately takes several minutes.
The `TargetTracking-inference-component/<ic>-AlarmHigh|Low` alarms belong to Application Auto Scaling. Deleting the policy removes them, so the script does not touch them (verified: no alarms remain after teardown).
## Async inference deployments
For long-running inferences (>60s), large payloads, or workloads that are bursty/sparse enough to benefit from scale-to-zero, use `deploy_async.py` instead of `deploy.py`. Async supports `MinCapacity=0` on the variant itself. Real-time endpoints also reach zero, but only through inference components — see "Scale to zero for real-time endpoints" below. Async remains the right choice when a single inference exceeds the 60s `InvokeEndpoint` response limit.
```bash
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://amzn-s3-demo-async-output/async-output/ \
--env HF_MODEL_ID=black-forest-labs/FLUX.1-dev
```
Required extras over `deploy.py`:
- `--output-s3-uri` — where async results land (results are not returned synchronously)
Optional async-specific flags:
- `--failure-s3-uri` — separate path for failed invocations
- `--success-sns-topic`, `--error-sns-topic` — get notified when async results are ready or fail
- `--min-capacity 0` (the default) — scale to zero between batches
- `--backlog-per-instance-target N` — target queue depth per instance (default 5)
- `--max-concurrent-invocations-per-instance N` — default 4
### How scale-to-zero works
The async script registers **two** autoscaling policies on the variant:
1. **Target-tracking** on `ApproximateBacklogSizePerInstance` — handles ongoing scaling between min and max
2. **Step-scaling** triggered by a `HasBacklogWithoutCapacity` CloudWatch alarm — handles `0→1` wake-from-zero
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:
- `ApproximateBacklogSize > 50` — queue is building faster than capacity can drain it
- `InvocationsFailed > 5` — repeated processing failures
- `HasBacklogWithoutCapacity` — drives the wake-from-zero policy (not a notification alarm; its action is the step-scaling policy, not the SNS topic)
If you pass `--sns-alarm-topic <arn>`, the first two notify on that topic. The wake alarm always points at the step policy.
### Invoking async endpoints
Async endpoints aren't called synchronously. You upload the input to S3, call `invoke-endpoint-async` with the S3 input location, and SageMaker writes the result to your `--output-s3-uri` when done:
```bash
# Upload your input first
aws s3 cp input.json s3://amzn-s3-demo-input/job1/input.json
# Invoke
aws sagemaker-runtime invoke-endpoint-async \
--endpoint-name <endpoint-name> \
--input-location s3://amzn-s3-demo-input/job1/input.json \
--content-type application/json \
--region <region>
# Poll for the result at your output URI
aws s3 cp s3://amzn-s3-demo-async-output/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).
## Defaults at a glance
| Setting | Default | Override |
|---|---|---|
| Initial instance count | 1 | `--initial-instance-count` |
| Autoscaling min / max | 1 / 4 | `--min-capacity`, `--max-capacity` |
| Autoscaling target | 20 invocations/min/instance | `--target-invocations-per-instance` |
| Data capture | disabled (opt-in) | `--enable-data-capture` |
| CloudWatch alarms | 3 alarms | `--no-alarms` |
| SNS notification | none (alarms created but won't notify) | `--sns-alarm-topic <arn>` |
| Environment tag | `dev` | `--environment` |
| InferenceAmiVersion | none (SageMaker default) | `--inference-ami-version` (REQUIRED for vLLM CUDA 13+) |
Not defaulted (user-specific input needed): VPC config, KMS key, multi-variant, async inference.
### Autoscaling target — tune by model type
The default `--target-invocations-per-instance 20` 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.
A 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 (`s3://sagemaker-<region>-<account>/<endpoint>/data-capture/`) is typically a different bucket than the model artifact bucket. If `hf-cloud-sagemaker-iam-preflight` scoped the inline policy narrowly to just the model bucket, capture writes fail silently — endpoint keeps serving but no data appears.
If the user reports "data capture isn't showing up", check the role's S3 access. Either widen the inline policy or pass `--data-capture-s3-uri` pointing to a bucket the role can write.
## Teardown
```bash
python3 scripts/teardown.py <endpoint-name> <region> # macOS / Linux
python scripts\teardown.py <endpoint-name> <region> # Windows
```
Deletes 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
**`CannotStartContainerError` + no CloudWatch logs ever created** — the InferenceAmiVersion problem. If the image tag contains `cu130` or later and you didn't pass `--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1`, this is the cause. See `hf-cloud-serving-image-selection`. Do NOT chase images, IAM roles, env vars, or instance types — the failure signature is identical for many other things but the cause here is the AMI.
**"Failed to pass ping health check"** — the container *did* start and produced logs, but `/ping` isn't responding. Check CloudWatch at `/aws/sagemaker/Endpoints/<endpoint-name>`. Usually: wrong image for model architecture, missing HF token, or OOM.
**"Container failed to start" (with logs present)** — entrypoint ran, then exited. Check CloudWatch. Common: missing required env vars (`SM_VLLM_MODEL`, `SM_VLLM_HOST`, `SM_VLLM_TRUST_REMOTE_CODE`), wrong `ModelDataUrl` format, unreadable model artifacts.
**`ResourceLimitExceeded`** — no quota for the instance type in this region. Request increase or pick a different type (the planner should have checked quotas up front — see `hf-cloud-sagemaker-deployment-planner`).
**`ImportError: libtorch_cuda.so: undefined symbol: ncclCommResume` in CloudWatch logs** — known packaging defect in `huggingface-pytorch-inference` GPU images (see "Known-broken images" in `hf-cloud-serving-image-selection`). Inside the container, so no env var, AMI, instance type, or sibling tag fixes it. Switch to DJL Inference.
**InService, 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 Forbidden` downloading weights from HF Hub during startup** — the container's bundled `huggingface_hub` predates HF's XET CDN auth. Add `--env HF_HUB_ENABLE_HF_TRANSFER=0`, or pre-stage the weights in S3. Note: this can *mask* a deeper failure (the worker may still crash after the download succeeds) — re-check logs after fixing it.
**Diagnostic 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.
**Component stuck in `Creating`, no `FailureReason`** — the container is crash-looping and supervisord restarts it, so the status never changes. The component holds `Creating` until `ContainerStartupHealthCheckTimeoutInSeconds` expires, up to an hour. Read `/aws/sagemaker/InferenceComponents/<component-name>` and look for `exited: app`, `not expected`, or `api_server.py: error:`. `deploy_ic.py` does this scan on every poll and aborts in about a minute.
**`There is not enough hardware resources on the instances for this endpoint`** — the component's `ComputeResourceRequirements` exceed the schedulable pool, which is much smaller than the instance memory. Lower `--min-memory-mb` (1024 works on `ml.g5.xlarge`; 4096 is rejected there). Do not add instances: the message appears with a healthy instance present.
**`Cannot delete inference component ... while it is in state CREATE_IN_PROGRESS` / `UPDATE_RC_IN_PROGRESS`** — normal, not an error. Retry; `teardown.py` retries for 15 min. `UPDATE_RC_IN_PROGRESS` means a scaling action is changing the copy count.
**A component outlives its endpoint** — `delete-endpoint` leaves components behind, still reporting `InService`. They block reuse of the name. Delete components first, which is what `teardown.py` does.
Don't retry blindly. The script prints the specific `FailureReason` from `describe-endpoint` — fix the root cause before retrying.
deployment-template.md 3.5 KB
# Production Defaults — What and Why
These defaults turn a working demo into something you can leave running. They favor "you'll find out about problems" over "absolute minimum cost". Tune any of them away if needed — the deployment script should be the starting point, not bare `create_endpoint`.
## Autoscaling — enabled, target tracking on invocations
| Setting | Default | Why |
|---|---|---|
| `MinCapacity` | 1 | Keep one warm. Min=0 enables scale-to-zero but adds cold-start latency on every gap. |
| `MaxCapacity` | 4 | Cap on scale-out. Raise for known peaks. |
| Target metric | `SageMakerVariantInvocationsPerInstance` | Scales on actual request load, not noisy GPU/CPU. |
| Target value | 20 invocations/min/instance | Conservative. Tune to model latency: faster model = higher target. |
| `ScaleInCooldown` | 300s | Long enough to avoid flapping. |
| `ScaleOutCooldown` | 60s | Scale out faster than in — under spikes, you want capacity now. |
For LLMs, the right target depends heavily on latency. A 100ms model handles 600/min easily; a 5s model maxes at ~12/min. 20 is a safe default for typical LLM latencies.
For embeddings (TEI), each request is much faster — typically <100ms on CPU and <20ms on GPU. The default of 20 will autoscale far too aggressively and waste money. Use `--target-invocations-per-instance 100–500` for embedding deployments. Rule of thumb: target ≈ 60 / (typical request latency in seconds).
## CloudWatch alarms — 3 by default
- **`ModelLatency` p99 > 30s for 5min** — slow inference, runaway requests, model loading issues.
- **`Invocation5XXErrors` sum > 5 in 5min** — container crashes, OOM, ping failures.
- **`OverheadLatency` p99 > 2s for 5min** — SageMaker platform issues, separate from model.
Without `--sns-alarm-topic`, alarms exist but don't notify. The deploy script warns when this happens.
## Data capture — disabled (opt-in via `--enable-data-capture`)
Useful for debugging "why did the model say that?" weeks later, building eval datasets, and audit trails for sensitive domains. But it creates ongoing S3 costs the user didn't necessarily ask for and stores data they may not realize is being kept — opt-in is the right default.
When enabled: 100% sampling, both input and output captured. URI defaults to `s3://sagemaker-<region>-<account>/<endpoint>/data-capture/`. Execution role needs write access to this prefix — if IAM was scoped narrowly to the model bucket, capture fails silently.
## Resource tagging
| Tag | Value |
|---|---|
| `Project` | User-supplied or model name |
| `Owner` | Caller ARN's user/email portion |
| `Environment` | `dev` (default) |
| `CreatedBy` | `agentic-deploy-skills` |
| `ModelArtifact` | S3 URI of the model |
`CreatedBy` matters most — `aws resourcegroupstaggingapi get-resources --tag-filters Key=CreatedBy,Values=agentic-deploy-skills` finds every resource these skills created.
## Endpoint naming
`<model-name>-<YYYYMMDD-HHMM>` by default. Timestamped names enable blue-green-ish iteration (bring up new, validate, delete old). Override with `--endpoint-name` if you have naming conventions.
## Not defaulted (need user input)
- **VPC config** — needs VPC ID + subnets
- **KMS encryption** — needs a specific key
- **Multi-variant endpoints** — uncommon enough that defaulting adds complexity
- **Async inference config** — different deployment pathway entirely
## Teardown
`python3 scripts/teardown.py <endpoint-name>` deletes endpoint → endpoint config → model in safe order. Autoscaling targets and alarms cleaned up separately. Data capture S3 objects are NOT deleted — that's the user's call.
_common.py 4.8 KB
"""Shared helpers for the deployment scripts (deploy.py, deploy_async.py).
Anything that should look identical between real-time and async deployments
lives here — tag schema, name format, env-var parsing, model creation,
endpoint waiting. Mode-specific logic (endpoint config shape, autoscaling
policies, alarm metrics) stays in the calling script.
"""
from __future__ import annotations
import sys
import time
from datetime import datetime, timezone
from typing import Any
from botocore.exceptions import ClientError
# Shared tagging convention. CreatedBy lets us find every resource these
# scripts have ever created via:
# aws resourcegroupstaggingapi get-resources \
# --tag-filters Key=CreatedBy,Values=agentic-deploy-skills
CREATED_BY_TAG_VALUE = "agentic-deploy-skills"
def log(prefix: str, msg: str) -> None:
"""Stream a log line to stderr with a per-script prefix."""
print(f"[{prefix}] {msg}", file=sys.stderr, flush=True)
def parse_env(env_args: list[str]) -> dict[str, str]:
"""Parse --env KEY=VALUE flags from argparse into a dict."""
env: dict[str, str] = {}
for item in env_args:
if "=" not in item:
raise SystemExit(f"--env must be KEY=VALUE, got: {item}")
k, v = item.split("=", 1)
env[k] = v
return env
def make_endpoint_name(model_name: str, override: str | None) -> str:
"""Generate a SageMaker-legal endpoint name.
Default format: <model-name>-<YYYYMMDD-HHMM>. SageMaker names are limited
to 63 chars and must be DNS-friendly (lowercase, hyphens, no underscores).
"""
if override:
return override
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M")
base = model_name.replace("_", "-").lower()
return f"{base}-{stamp}"[:63]
def build_tags(
*,
project: str,
caller_arn: str,
environment: str,
model_s3_uri: str | None = None,
extra: dict[str, str] | None = None,
) -> list[dict[str, str]]:
"""Build the shared tag set applied to every resource we create.
`extra` lets the caller add deployment-mode-specific tags (e.g.
`{"InferenceMode": "async"}`) without forking the schema.
"""
owner = caller_arn.split("/")[-1] if "/" in caller_arn else caller_arn
tags = [
{"Key": "Project", "Value": project},
{"Key": "Owner", "Value": owner},
{"Key": "Environment", "Value": environment},
{"Key": "CreatedBy", "Value": CREATED_BY_TAG_VALUE},
]
if model_s3_uri:
tags.append({"Key": "ModelArtifact", "Value": model_s3_uri})
if extra:
for k, v in extra.items():
tags.append({"Key": k, "Value": v})
return tags
def create_model(
sm: Any,
*,
model_name: str,
image_uri: str,
role_arn: str,
model_s3_uri: str | None,
env: dict[str, str],
tags: list[dict[str, str]],
log_prefix: str = "deploy",
) -> str:
"""Create a SageMaker Model. Idempotent — reuses on AlreadyExists.
Returns the model name on success. The model definition itself is mode-
independent: same call, same parameters, whether the eventual endpoint
is real-time or async.
"""
log(log_prefix, f"Creating model: {model_name}")
primary_container: dict[str, Any] = {"Image": image_uri}
if env:
primary_container["Environment"] = env
if model_s3_uri:
primary_container["ModelDataUrl"] = model_s3_uri
try:
sm.create_model(
ModelName=model_name,
PrimaryContainer=primary_container,
ExecutionRoleArn=role_arn,
Tags=tags,
)
except ClientError as e:
if "Cannot create already existing model" in str(e):
log(log_prefix, f"Model {model_name} already exists — reusing")
else:
raise
return model_name
def wait_for_endpoint(
sm: Any,
endpoint_name: str,
timeout_minutes: int = 30,
log_prefix: str = "deploy",
) -> None:
"""Poll DescribeEndpoint until InService, or raise on Failed/timeout."""
log(log_prefix, f"Waiting for {endpoint_name} to reach InService (up to {timeout_minutes} min)...")
start = time.time()
deadline = start + (timeout_minutes * 60)
while time.time() < deadline:
resp = sm.describe_endpoint(EndpointName=endpoint_name)
status = resp["EndpointStatus"]
elapsed = int(time.time() - start)
if status == "InService":
log(log_prefix, f"InService after {elapsed}s")
return
if status == "Failed":
reason = resp.get("FailureReason", "(no reason given)")
raise RuntimeError(f"Endpoint creation failed after {elapsed}s: {reason}")
log(log_prefix, f" status={status} elapsed={elapsed}s")
time.sleep(30)
raise TimeoutError(f"Endpoint did not reach InService within {timeout_minutes} minutes")
deploy.py 12.7 KB
#!/usr/bin/env python
"""Create a SageMaker real-time endpoint with production defaults.
Minimal usage:
python deploy.py --model-name <name> --image-uri <uri> \
--inference-ami-version <ami> --role-arn <arn> \
--instance-type ml.g5.xlarge --region <region>
See the SKILL.md for full flags and the recommended chained-with-resolver pattern.
"""
import argparse
import json
import sys
import time
from typing import Any
import boto3
from botocore.exceptions import ClientError
from _common import (
build_tags,
create_model,
log as _log,
make_endpoint_name,
parse_env,
wait_for_endpoint,
)
# Defaults — change here, not at call sites.
# Reasoning lives in references/deployment-template.md.
DEFAULTS = {
"initial_instance_count": 1,
"min_capacity": 1,
"max_capacity": 4,
"target_invocations_per_instance": 20,
"scale_in_cooldown_seconds": 300,
"scale_out_cooldown_seconds": 60,
"data_capture_sampling_percent": 100,
"alarm_latency_threshold_ms": 30_000,
"alarm_5xx_threshold_count": 5,
"alarm_overhead_threshold_ms": 2_000,
"alarm_evaluation_periods": 1,
"alarm_period_seconds": 300,
"environment_tag": "dev",
}
def log(msg: str) -> None:
_log("deploy", msg)
def create_endpoint_config(
sm: Any, *, config_name: str, model_name: str, instance_type: str,
initial_instance_count: int, inference_ami_version: str | None,
data_capture_enabled: bool, data_capture_s3_uri: str | None,
tags: list[dict],
) -> str:
log(f"Creating endpoint config: {config_name}")
production_variant: dict[str, Any] = {
"VariantName": "AllTraffic",
"ModelName": model_name,
"InstanceType": instance_type,
"InitialInstanceCount": initial_instance_count,
"InitialVariantWeight": 1.0,
}
# InferenceAmiVersion required for vLLM DLC with CUDA 13+. Without it the
# container dies on startup with no logs. See hf-cloud-serving-image-selection skill.
if inference_ami_version:
production_variant["InferenceAmiVersion"] = inference_ami_version
log(f" InferenceAmiVersion set to: {inference_ami_version}")
kwargs: dict[str, Any] = {
"EndpointConfigName": config_name,
"ProductionVariants": [production_variant],
"Tags": tags,
}
if data_capture_enabled:
if not data_capture_s3_uri:
raise ValueError("data_capture_enabled but no data_capture_s3_uri provided")
kwargs["DataCaptureConfig"] = {
"EnableCapture": True,
"InitialSamplingPercentage": DEFAULTS["data_capture_sampling_percent"],
"DestinationS3Uri": data_capture_s3_uri,
"CaptureOptions": [{"CaptureMode": "Input"}, {"CaptureMode": "Output"}],
"CaptureContentTypeHeader": {"JsonContentTypes": ["application/json"]},
}
try:
sm.create_endpoint_config(**kwargs)
except ClientError as e:
if "Cannot create already existing endpoint configuration" in str(e):
log(f"Endpoint config {config_name} already exists — reusing")
else:
raise
return config_name
def create_endpoint(sm: Any, *, endpoint_name: str, config_name: str, tags: list[dict]) -> None:
log(f"Creating endpoint: {endpoint_name}")
sm.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=config_name,
Tags=tags,
)
def register_autoscaling(
*, endpoint_name: str, variant_name: str, min_capacity: int, max_capacity: int,
target_invocations: int, scale_in_cooldown: int, scale_out_cooldown: int, region: str,
) -> None:
log(f"Registering autoscaling: min={min_capacity} max={max_capacity} target={target_invocations}/min")
appscaling = boto3.client("application-autoscaling", region_name=region)
resource_id = f"endpoint/{endpoint_name}/variant/{variant_name}"
appscaling.register_scalable_target(
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
MinCapacity=min_capacity,
MaxCapacity=max_capacity,
)
appscaling.put_scaling_policy(
PolicyName=f"{endpoint_name}-target-tracking",
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
PolicyType="TargetTrackingScaling",
TargetTrackingScalingPolicyConfiguration={
"TargetValue": float(target_invocations),
"PredefinedMetricSpecification": {
"PredefinedMetricType": "SageMakerVariantInvocationsPerInstance",
},
"ScaleInCooldown": scale_in_cooldown,
"ScaleOutCooldown": scale_out_cooldown,
},
)
def create_alarms(*, endpoint_name: str, variant_name: str, sns_topic_arn: str | None, region: str) -> None:
log(f"Creating CloudWatch alarms for {endpoint_name}")
cw = boto3.client("cloudwatch", region_name=region)
actions = [sns_topic_arn] if sns_topic_arn else []
common_dims = [
{"Name": "EndpointName", "Value": endpoint_name},
{"Name": "VariantName", "Value": variant_name},
]
alarms = [
{
"AlarmName": f"{endpoint_name}-ModelLatencyP99",
"MetricName": "ModelLatency",
"ExtendedStatistic": "p99",
"Threshold": DEFAULTS["alarm_latency_threshold_ms"] * 1000, # microseconds
"ComparisonOperator": "GreaterThanThreshold",
"AlarmDescription": "Model inference latency p99 > 30s",
},
{
"AlarmName": f"{endpoint_name}-Invocation5XXErrors",
"MetricName": "Invocation5XXErrors",
"Statistic": "Sum",
"Threshold": DEFAULTS["alarm_5xx_threshold_count"],
"ComparisonOperator": "GreaterThanThreshold",
"AlarmDescription": "5XX errors > 5 in 5min",
},
{
"AlarmName": f"{endpoint_name}-OverheadLatencyP99",
"MetricName": "OverheadLatency",
"ExtendedStatistic": "p99",
"Threshold": DEFAULTS["alarm_overhead_threshold_ms"] * 1000,
"ComparisonOperator": "GreaterThanThreshold",
"AlarmDescription": "Platform overhead latency p99 > 2s",
},
]
for spec in alarms:
params = {
"AlarmName": spec["AlarmName"],
"AlarmDescription": spec["AlarmDescription"],
"MetricName": spec["MetricName"],
"Namespace": "AWS/SageMaker",
"Dimensions": common_dims,
"Period": DEFAULTS["alarm_period_seconds"],
"EvaluationPeriods": DEFAULTS["alarm_evaluation_periods"],
"Threshold": spec["Threshold"],
"ComparisonOperator": spec["ComparisonOperator"],
"TreatMissingData": "notBreaching",
"AlarmActions": actions,
}
if "Statistic" in spec:
params["Statistic"] = spec["Statistic"]
if "ExtendedStatistic" in spec:
params["ExtendedStatistic"] = spec["ExtendedStatistic"]
cw.put_metric_alarm(**params)
if not sns_topic_arn:
log("WARNING: no --sns-alarm-topic — alarms exist but won't notify anyone.")
def main() -> int:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
# Required
p.add_argument("--model-name", required=True)
p.add_argument("--image-uri", required=True, help="From hf-cloud-serving-image-selection")
p.add_argument("--role-arn", required=True, help="From hf-cloud-sagemaker-iam-preflight")
p.add_argument("--instance-type", required=True, help="e.g. ml.g5.xlarge")
p.add_argument("--region", required=True, help="From hf-cloud-aws-context-discovery")
# Conditional
p.add_argument("--model-s3-uri", default=None,
help="S3 model artifact extracted to /opt/ml/model (preferred); omit only for Hub-at-runtime")
p.add_argument("--env", action="append", default=[], help="KEY=VALUE; repeatable")
p.add_argument(
"--inference-ami-version", default=None,
help=(
"REQUIRED for vLLM DLC with CUDA 13+ (e.g. al2-ami-sagemaker-inference-gpu-3-1). "
"Without this, container dies on startup with no logs. "
"See hf-cloud-serving-image-selection's 'vLLM AMI requirement' table to map a tag to the AMI version."
),
)
# Naming
p.add_argument("--endpoint-name", default=None, help="Default: <model-name>-<timestamp>")
p.add_argument("--project", default=None, help="Tag value (default: model name)")
p.add_argument("--environment", default=DEFAULTS["environment_tag"])
# Capacity / scaling
p.add_argument("--initial-instance-count", type=int, default=DEFAULTS["initial_instance_count"])
p.add_argument("--min-capacity", type=int, default=DEFAULTS["min_capacity"])
p.add_argument("--max-capacity", type=int, default=DEFAULTS["max_capacity"])
p.add_argument("--target-invocations-per-instance", type=int, default=DEFAULTS["target_invocations_per_instance"])
p.add_argument("--no-autoscaling", action="store_true", help="NOT RECOMMENDED")
# Data capture (off by default)
p.add_argument("--enable-data-capture", action="store_true", help="Log requests/responses to S3")
p.add_argument("--data-capture-s3-uri", default=None)
# Alarms
p.add_argument("--sns-alarm-topic", default=None, help="SNS topic ARN for alarm notifications")
p.add_argument("--no-alarms", action="store_true")
args = p.parse_args()
env_dict = parse_env(args.env)
endpoint_name = make_endpoint_name(args.model_name, args.endpoint_name)
config_name = f"{endpoint_name}-config"
sts = boto3.client("sts", region_name=args.region)
sm = boto3.client("sagemaker", region_name=args.region)
caller_arn = sts.get_caller_identity()["Arn"]
account_id = sts.get_caller_identity()["Account"]
if args.enable_data_capture and not args.data_capture_s3_uri:
args.data_capture_s3_uri = f"s3://sagemaker-{args.region}-{account_id}/{endpoint_name}/data-capture/"
log(f"Data capture URI defaulted to: {args.data_capture_s3_uri}")
tags = build_tags(
project=args.project or args.model_name,
caller_arn=caller_arn,
environment=args.environment,
model_s3_uri=args.model_s3_uri,
)
create_model(
sm, model_name=args.model_name, image_uri=args.image_uri,
role_arn=args.role_arn, model_s3_uri=args.model_s3_uri,
env=env_dict, tags=tags, log_prefix="deploy",
)
create_endpoint_config(
sm, config_name=config_name, model_name=args.model_name,
instance_type=args.instance_type, initial_instance_count=args.initial_instance_count,
inference_ami_version=args.inference_ami_version,
data_capture_enabled=args.enable_data_capture,
data_capture_s3_uri=args.data_capture_s3_uri, tags=tags,
)
create_endpoint(sm, endpoint_name=endpoint_name, config_name=config_name, tags=tags)
wait_for_endpoint(sm, endpoint_name, log_prefix="deploy")
if not args.no_autoscaling:
register_autoscaling(
endpoint_name=endpoint_name, variant_name="AllTraffic",
min_capacity=args.min_capacity, max_capacity=args.max_capacity,
target_invocations=args.target_invocations_per_instance,
scale_in_cooldown=DEFAULTS["scale_in_cooldown_seconds"],
scale_out_cooldown=DEFAULTS["scale_out_cooldown_seconds"],
region=args.region,
)
else:
log("WARNING: autoscaling skipped. Endpoint won't scale with traffic.")
if not args.no_alarms:
create_alarms(
endpoint_name=endpoint_name, variant_name="AllTraffic",
sns_topic_arn=args.sns_alarm_topic, region=args.region,
)
# Summary
log("")
log(f"Deployment complete: {endpoint_name}")
log(f" Instance: {args.instance_type}")
log(f" Autoscaling: {'OFF' if args.no_autoscaling else f'{args.min_capacity}-{args.max_capacity} instances'}")
log(f" Data capture: {args.data_capture_s3_uri if args.enable_data_capture else 'OFF (pass --enable-data-capture)'}")
log("")
log(f"Test: python3 invoke_endpoint.py --endpoint-name {endpoint_name} \\")
log(f" --payload '{{\"prompt\": \"hello\"}}' --region {args.region}")
log(" (BOM-safe + cross-platform; use 'python' on Windows)")
log(f"Teardown: python3 teardown.py {endpoint_name} {args.region}")
# Machine-readable summary for downstream scripting
print(json.dumps({
"endpoint_name": endpoint_name,
"endpoint_config_name": config_name,
"model_name": args.model_name,
"region": args.region,
"instance_type": args.instance_type,
}))
return 0
if __name__ == "__main__":
sys.exit(main())
deploy_async.py 18.1 KB
#!/usr/bin/env python
"""Create a SageMaker async-inference endpoint with production defaults.
Minimal usage:
python deploy_async.py --model-name <name> --image-uri <uri> \
--role-arn <arn> --instance-type ml.g5.xlarge --region <region> \
--output-s3-uri s3://bucket/path/
Async differs from real-time in three structural ways:
1. AsyncInferenceConfig on the endpoint config (S3 output path, optional
SNS notification topics, optional failure path)
2. Autoscaling MinCapacity=0 is supported — endpoints can genuinely scale
to zero between batches. Target-tracking on ApproximateBacklogSizePerInstance.
3. Scale-from-zero (0→1) requires a SEPARATE step-scaling policy bound to
a HasBacklogWithoutCapacity alarm. Target-tracking alone can't transition
from zero, so without the step policy the endpoint won't wake up.
See SKILL.md for the recommended chained-with-resolver pattern.
"""
import argparse
import json
import sys
from typing import Any
import boto3
from botocore.exceptions import ClientError
from _common import (
build_tags,
create_model,
log as _log,
make_endpoint_name,
parse_env,
wait_for_endpoint,
)
# Defaults — change here, not at call sites.
DEFAULTS = {
"initial_instance_count": 1,
"min_capacity": 0, # async genuinely supports scale-to-zero
"max_capacity": 4,
"backlog_per_instance_target": 5, # target queue depth per instance
"scale_in_cooldown_seconds": 600, # slower scale-in for async — batches are bursty
"scale_out_cooldown_seconds": 60,
"wake_from_zero_step_size": 1, # 0→1 instance when backlog appears
"max_concurrent_invocations_per_instance": 4,
# Alarms
"alarm_backlog_size_threshold": 50, # queue too deep
"alarm_failed_invocations_threshold": 5, # repeated failures
"alarm_evaluation_periods": 1,
"alarm_period_seconds": 60, # async needs faster eval for wake-from-zero
"environment_tag": "dev",
}
def log(msg: str) -> None:
_log("deploy_async", msg)
def create_async_endpoint_config(
sm: Any, *, config_name: str, model_name: str, instance_type: str,
initial_instance_count: int, inference_ami_version: str | None,
output_s3_uri: str, failure_s3_uri: str | None,
success_topic_arn: str | None, error_topic_arn: str | None,
max_concurrent_invocations: int,
tags: list[dict],
) -> str:
log(f"Creating async endpoint config: {config_name}")
production_variant: dict[str, Any] = {
"VariantName": "AllTraffic",
"ModelName": model_name,
"InstanceType": instance_type,
"InitialInstanceCount": initial_instance_count,
"InitialVariantWeight": 1.0,
}
if inference_ami_version:
production_variant["InferenceAmiVersion"] = inference_ami_version
log(f" InferenceAmiVersion set to: {inference_ami_version}")
output_config: dict[str, Any] = {"S3OutputPath": output_s3_uri}
if failure_s3_uri:
output_config["S3FailurePath"] = failure_s3_uri
if success_topic_arn or error_topic_arn:
notification: dict[str, str] = {}
if success_topic_arn:
notification["SuccessTopic"] = success_topic_arn
if error_topic_arn:
notification["ErrorTopic"] = error_topic_arn
output_config["NotificationConfig"] = notification
async_config: dict[str, Any] = {
"OutputConfig": output_config,
"ClientConfig": {
"MaxConcurrentInvocationsPerInstance": max_concurrent_invocations,
},
}
kwargs: dict[str, Any] = {
"EndpointConfigName": config_name,
"ProductionVariants": [production_variant],
"AsyncInferenceConfig": async_config,
"Tags": tags,
}
try:
sm.create_endpoint_config(**kwargs)
except ClientError as e:
if "Cannot create already existing endpoint configuration" in str(e):
log(f"Endpoint config {config_name} already exists — reusing")
else:
raise
return config_name
def create_endpoint(sm: Any, *, endpoint_name: str, config_name: str, tags: list[dict]) -> None:
log(f"Creating endpoint: {endpoint_name}")
sm.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=config_name,
Tags=tags,
)
def register_async_autoscaling(
*, endpoint_name: str, variant_name: str, min_capacity: int, max_capacity: int,
backlog_per_instance_target: int, scale_in_cooldown: int, scale_out_cooldown: int,
wake_step_size: int, region: str,
) -> None:
"""Register two autoscaling policies on the variant:
1. Target-tracking on ApproximateBacklogSizePerInstance — handles
ongoing scaling between MinCapacity and MaxCapacity.
2. Step-scaling that increments capacity by `wake_step_size` when
triggered — needed for 0→1 wake-from-zero, because target-tracking
can't transition from zero capacity.
The step-scaling policy is invoked by a HasBacklogWithoutCapacity alarm
(created separately in create_async_alarms).
"""
log(f"Registering async autoscaling: min={min_capacity} max={max_capacity} backlog-target={backlog_per_instance_target}")
appscaling = boto3.client("application-autoscaling", region_name=region)
resource_id = f"endpoint/{endpoint_name}/variant/{variant_name}"
appscaling.register_scalable_target(
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
MinCapacity=min_capacity,
MaxCapacity=max_capacity,
)
# (1) Target-tracking for ongoing scaling between min and max
appscaling.put_scaling_policy(
PolicyName=f"{endpoint_name}-backlog-target-tracking",
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
PolicyType="TargetTrackingScaling",
TargetTrackingScalingPolicyConfiguration={
"TargetValue": float(backlog_per_instance_target),
"CustomizedMetricSpecification": {
"MetricName": "ApproximateBacklogSizePerInstance",
"Namespace": "AWS/SageMaker",
"Dimensions": [{"Name": "EndpointName", "Value": endpoint_name}],
"Statistic": "Average",
},
"ScaleInCooldown": scale_in_cooldown,
"ScaleOutCooldown": scale_out_cooldown,
},
)
# (2) Step-scaling for wake-from-zero. The CloudWatch alarm bound to
# this policy is created in create_async_alarms.
appscaling.put_scaling_policy(
PolicyName=f"{endpoint_name}-step-wake-from-zero",
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
PolicyType="StepScaling",
StepScalingPolicyConfiguration={
"AdjustmentType": "ChangeInCapacity",
"MetricAggregationType": "Maximum",
"Cooldown": scale_out_cooldown,
"StepAdjustments": [
{
"MetricIntervalLowerBound": 0,
"ScalingAdjustment": wake_step_size,
},
],
},
)
def create_async_alarms(
*, endpoint_name: str, variant_name: str, sns_topic_arn: str | None,
region: str, wake_alarm_arns_for_step_policy: list[str],
) -> None:
"""Create CloudWatch alarms for the async endpoint, including the
HasBacklogWithoutCapacity alarm that drives the wake-from-zero policy.
"""
log(f"Creating CloudWatch alarms for {endpoint_name}")
cw = boto3.client("cloudwatch", region_name=region)
actions = [sns_topic_arn] if sns_topic_arn else []
endpoint_dim = [{"Name": "EndpointName", "Value": endpoint_name}]
# 1. Backlog too deep — capacity is keeping up poorly with incoming requests
cw.put_metric_alarm(
AlarmName=f"{endpoint_name}-ApproximateBacklogSize",
AlarmDescription="Async queue backlog too deep",
MetricName="ApproximateBacklogSize",
Namespace="AWS/SageMaker",
Dimensions=endpoint_dim,
Statistic="Average",
Period=DEFAULTS["alarm_period_seconds"],
EvaluationPeriods=DEFAULTS["alarm_evaluation_periods"],
Threshold=DEFAULTS["alarm_backlog_size_threshold"],
ComparisonOperator="GreaterThanThreshold",
TreatMissingData="notBreaching",
AlarmActions=actions,
)
# 2. InvocationsFailed — repeated client/server errors in async processing
cw.put_metric_alarm(
AlarmName=f"{endpoint_name}-InvocationsFailed",
AlarmDescription="Async invocations failing repeatedly",
MetricName="InvocationsFailed",
Namespace="AWS/SageMaker",
Dimensions=endpoint_dim,
Statistic="Sum",
Period=DEFAULTS["alarm_period_seconds"],
EvaluationPeriods=DEFAULTS["alarm_evaluation_periods"],
Threshold=DEFAULTS["alarm_failed_invocations_threshold"],
ComparisonOperator="GreaterThanThreshold",
TreatMissingData="notBreaching",
AlarmActions=actions,
)
# 3. HasBacklogWithoutCapacity — drives the step-scaling wake-from-zero
# policy. The Alarm action is the step policy ARN, not the SNS topic.
cw.put_metric_alarm(
AlarmName=f"{endpoint_name}-HasBacklogWithoutCapacity",
AlarmDescription="Async backlog exists but no instances running — triggers wake-from-zero",
MetricName="HasBacklogWithoutCapacity",
Namespace="AWS/SageMaker",
Dimensions=endpoint_dim,
Statistic="Average",
Period=60, # tight evaluation: we want fast wake-up
EvaluationPeriods=1,
Threshold=1,
ComparisonOperator="GreaterThanOrEqualToThreshold",
TreatMissingData="notBreaching",
AlarmActions=wake_alarm_arns_for_step_policy, # step policy ARNs
)
if not sns_topic_arn:
log("WARNING: no --sns-alarm-topic — backlog/failure alarms exist but won't notify anyone.")
def get_step_policy_arn(*, endpoint_name: str, variant_name: str, region: str) -> str:
"""Look up the ARN of the step-scaling policy we just created.
`put_scaling_policy` returns the ARN on creation but we don't capture it
above to keep the function signature small. Re-fetch via describe.
"""
appscaling = boto3.client("application-autoscaling", region_name=region)
resp = appscaling.describe_scaling_policies(
ServiceNamespace="sagemaker",
ResourceId=f"endpoint/{endpoint_name}/variant/{variant_name}",
PolicyNames=[f"{endpoint_name}-step-wake-from-zero"],
)
policies = resp.get("ScalingPolicies", [])
if not policies:
raise RuntimeError(f"Step-scaling policy not found for {endpoint_name} — was register_async_autoscaling called?")
return policies[0]["PolicyARN"]
def main() -> int:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
# Required
p.add_argument("--model-name", required=True)
p.add_argument("--image-uri", required=True, help="From hf-cloud-serving-image-selection")
p.add_argument("--role-arn", required=True, help="From hf-cloud-sagemaker-iam-preflight")
p.add_argument("--instance-type", required=True, help="e.g. ml.g5.xlarge")
p.add_argument("--region", required=True, help="From hf-cloud-aws-context-discovery")
p.add_argument("--output-s3-uri", required=True,
help="S3 path where async results are written. e.g. s3://amzn-s3-demo-async-output/async-output/")
# Conditional
p.add_argument("--model-s3-uri", default=None,
help="S3 model artifact extracted to /opt/ml/model (preferred); omit only for Hub-at-runtime")
p.add_argument("--env", action="append", default=[], help="KEY=VALUE; repeatable")
p.add_argument("--inference-ami-version", default=None,
help="REQUIRED for vLLM DLC with CUDA 13+ (e.g. al2-ami-sagemaker-inference-gpu-3-1)")
p.add_argument("--failure-s3-uri", default=None,
help="S3 path for failed async invocations (optional; default: errors written to OutputConfig.S3OutputPath)")
p.add_argument("--success-sns-topic", default=None,
help="SNS topic ARN notified when async invocation succeeds")
p.add_argument("--error-sns-topic", default=None,
help="SNS topic ARN notified when async invocation fails")
# Naming
p.add_argument("--endpoint-name", default=None, help="Default: <model-name>-<timestamp>")
p.add_argument("--project", default=None, help="Tag value (default: model name)")
p.add_argument("--environment", default=DEFAULTS["environment_tag"])
# Capacity / scaling
p.add_argument("--initial-instance-count", type=int, default=DEFAULTS["initial_instance_count"])
p.add_argument("--min-capacity", type=int, default=DEFAULTS["min_capacity"],
help="Async supports 0 (scale-to-zero between batches). Default 0.")
p.add_argument("--max-capacity", type=int, default=DEFAULTS["max_capacity"])
p.add_argument("--backlog-per-instance-target", type=int,
default=DEFAULTS["backlog_per_instance_target"],
help="Target queue depth per instance for autoscaling")
p.add_argument("--max-concurrent-invocations-per-instance", type=int,
default=DEFAULTS["max_concurrent_invocations_per_instance"])
p.add_argument("--no-autoscaling", action="store_true",
help="NOT RECOMMENDED for async — endpoint won't scale to zero")
# Alarms
p.add_argument("--sns-alarm-topic", default=None, help="SNS topic ARN for backlog/failure alarms")
p.add_argument("--no-alarms", action="store_true")
args = p.parse_args()
env_dict = parse_env(args.env)
endpoint_name = make_endpoint_name(args.model_name, args.endpoint_name)
config_name = f"{endpoint_name}-config"
sts = boto3.client("sts", region_name=args.region)
sm = boto3.client("sagemaker", region_name=args.region)
caller_arn = sts.get_caller_identity()["Arn"]
if args.min_capacity == 0 and args.no_autoscaling:
raise SystemExit(
"--min-capacity 0 requires autoscaling to be enabled (the wake-from-zero "
"policy is what brings instances up). Either remove --no-autoscaling or "
"set --min-capacity 1."
)
tags = build_tags(
project=args.project or args.model_name,
caller_arn=caller_arn,
environment=args.environment,
model_s3_uri=args.model_s3_uri,
extra={"InferenceMode": "async"},
)
create_model(
sm, model_name=args.model_name, image_uri=args.image_uri,
role_arn=args.role_arn, model_s3_uri=args.model_s3_uri,
env=env_dict, tags=tags, log_prefix="deploy_async",
)
create_async_endpoint_config(
sm, config_name=config_name, model_name=args.model_name,
instance_type=args.instance_type,
initial_instance_count=args.initial_instance_count,
inference_ami_version=args.inference_ami_version,
output_s3_uri=args.output_s3_uri,
failure_s3_uri=args.failure_s3_uri,
success_topic_arn=args.success_sns_topic,
error_topic_arn=args.error_sns_topic,
max_concurrent_invocations=args.max_concurrent_invocations_per_instance,
tags=tags,
)
create_endpoint(sm, endpoint_name=endpoint_name, config_name=config_name, tags=tags)
wait_for_endpoint(sm, endpoint_name, log_prefix="deploy_async")
if not args.no_autoscaling:
register_async_autoscaling(
endpoint_name=endpoint_name, variant_name="AllTraffic",
min_capacity=args.min_capacity, max_capacity=args.max_capacity,
backlog_per_instance_target=args.backlog_per_instance_target,
scale_in_cooldown=DEFAULTS["scale_in_cooldown_seconds"],
scale_out_cooldown=DEFAULTS["scale_out_cooldown_seconds"],
wake_step_size=DEFAULTS["wake_from_zero_step_size"],
region=args.region,
)
# The wake-from-zero alarm needs the step policy's ARN as its action.
step_policy_arn = get_step_policy_arn(
endpoint_name=endpoint_name, variant_name="AllTraffic", region=args.region,
)
else:
log("WARNING: autoscaling skipped. Endpoint will NOT scale (in either direction).")
step_policy_arn = None
if not args.no_alarms:
create_async_alarms(
endpoint_name=endpoint_name, variant_name="AllTraffic",
sns_topic_arn=args.sns_alarm_topic, region=args.region,
wake_alarm_arns_for_step_policy=[step_policy_arn] if step_policy_arn else [],
)
# Summary
log("")
log(f"Async deployment complete: {endpoint_name}")
log(f" Instance: {args.instance_type}")
if args.no_autoscaling:
autoscaling_summary = "OFF"
else:
zero_label = "enabled" if args.min_capacity == 0 else "disabled"
autoscaling_summary = f"{args.min_capacity}-{args.max_capacity} instances (scale-to-zero {zero_label})"
log(f" Autoscaling: {autoscaling_summary}")
log(f" Output S3 path: {args.output_s3_uri}")
log(f" Notifications: success={args.success_sns_topic or 'none'} error={args.error_sns_topic or 'none'}")
log("")
log("Invoke (async, via S3 input location):")
log(f" aws sagemaker-runtime invoke-endpoint-async \\")
log(f" --endpoint-name {endpoint_name} \\")
log(f" --input-location s3://YOUR-INPUT-BUCKET/path/to/input.json \\")
log(f" --content-type application/json --region {args.region}")
log(f" # Result will land at: {args.output_s3_uri}")
log(" # Write input.json as BOM-free UTF-8 (on Windows, NOT 'Set-Content -Encoding UTF8')")
log("")
log(f"Teardown: python3 teardown.py {endpoint_name} {args.region}")
print(json.dumps({
"endpoint_name": endpoint_name,
"endpoint_config_name": config_name,
"model_name": args.model_name,
"region": args.region,
"instance_type": args.instance_type,
"inference_mode": "async",
"output_s3_uri": args.output_s3_uri,
}))
return 0
if __name__ == "__main__":
sys.exit(main())
deploy_ic.py 20.2 KB
#!/usr/bin/env python
"""Create a real-time SageMaker endpoint that scales to ZERO instances.
Real-time scale-to-zero requires inference components. The endpoint hosts no
model directly; a component carries the model and its copy count is the thing
that scales, down to zero.
Minimal usage:
python deploy_ic.py --model-name <name> --image-uri <uri> \
--inference-ami-version <ami> --role-arn <arn> \
--instance-type ml.g5.xlarge --region <region> \
--model-s3-uri s3://<your-model-bucket>/<model>/model.tar.gz \
--env SM_VLLM_MODEL=/opt/ml/model --env SM_VLLM_HOST=0.0.0.0 \
--env SM_VLLM_TRUST_REMOTE_CODE=false
Four pieces make zero work, and all four are required:
1. endpoint config: ManagedInstanceScaling with MinInstanceCount=0
2. scalable target on inference-component/<name> with MinCapacity=0
3. target-tracking policy on concurrency (handles 1..n)
4. step-scaling policy + NoCapacityInvocationFailures alarm (handles 0 -> 1)
Target tracking alone cannot leave zero, so without (4) the endpoint scales to
zero once and never wakes.
Measured on ml.g5.xlarge with Qwen3-0.6B from the Hub (July 2026):
endpoint InService 4 min (it starts empty) -> component InService +6 min ->
idle scale-in to 0 copies 11 min -> 0 instances +12 min -> wake from zero
9 min 24 s from the first rejected request to a 200.
See SKILL.md, section "Scale to zero for real-time endpoints".
"""
import argparse
import json
import sys
import time
from typing import Any
import boto3
from botocore.exceptions import ClientError
from _common import (
build_tags,
create_model,
log as _log,
make_endpoint_name,
parse_env,
wait_for_endpoint,
)
# Defaults — change here, not at call sites.
DEFAULTS = {
"initial_instance_count": 1,
"min_instance_count": 0,
"max_instance_count": 2,
"min_copy_count": 0,
"max_copy_count": 4,
# Concurrent requests per copy. Target tracking scales out above this.
"concurrency_target_per_copy": 5,
"scale_in_cooldown_seconds": 300,
"scale_out_cooldown_seconds": 300,
"wake_cooldown_seconds": 60,
"wake_step_size": 1,
"model_data_download_timeout": 3600,
# 3600 is the API maximum, but a crash-looping container holds the component
# in Creating for the whole timeout. 1800 plus the log scan below surfaces a
# broken container in about a minute instead.
"container_startup_timeout": 1800,
# A scheduling reservation, not a cap: the container may use more. Keep it
# small. ml.g5.xlarge accepts 1024 and rejects 4096, far below its 16 GiB.
"min_memory_required_mb": 1024,
"accelerator_devices": 1,
"alarm_evaluation_periods": 1,
"alarm_period_seconds": 300,
"alarm_5xx_threshold_count": 5,
"environment_tag": "dev",
}
IC_DIMENSION = "sagemaker:inference-component:DesiredCopyCount"
# High-resolution concurrency, not invocations/minute: it reacts up to 6x faster
# and its idle zeros are what drive scale-in to zero.
CONCURRENCY_METRIC = "SageMakerInferenceComponentConcurrentRequestsPerCopyHighResolution"
WAKE_METRIC = "NoCapacityInvocationFailures"
# supervisord restarts a dying server, so the component status stays Creating.
# These markers are the only early evidence of a crash loop.
CRASH_MARKERS = (
"exited: app",
"not expected",
"Worker died",
"Load model failed",
"ImportError",
"Traceback (most recent call last)",
"api_server.py: error:",
)
def log(msg: str) -> None:
_log("deploy_ic", msg)
def create_endpoint_config(
sm: Any, *, config_name: str, instance_type: str, role_arn: str,
initial_instance_count: int, min_instance_count: int, max_instance_count: int,
inference_ami_version: str | None, tags: list[dict],
) -> str:
log(f"Creating IC endpoint config: {config_name}")
variant: dict[str, Any] = {
"VariantName": "AllTraffic",
"InstanceType": instance_type,
"InitialInstanceCount": initial_instance_count,
"ModelDataDownloadTimeoutInSeconds": DEFAULTS["model_data_download_timeout"],
"ContainerStartupHealthCheckTimeoutInSeconds": DEFAULTS["container_startup_timeout"],
# MinInstanceCount=0 is what allows the endpoint to drop every instance.
"ManagedInstanceScaling": {
"Status": "ENABLED",
"MinInstanceCount": min_instance_count,
"MaxInstanceCount": max_instance_count,
},
"RoutingConfig": {"RoutingStrategy": "LEAST_OUTSTANDING_REQUESTS"},
}
# Same vLLM CUDA 13+ rule as deploy.py, and it coexists with
# ManagedInstanceScaling on the same variant (verified).
if inference_ami_version:
variant["InferenceAmiVersion"] = inference_ami_version
log(f" InferenceAmiVersion set to: {inference_ami_version}")
# Two differences from a model-based config: no ModelName on the variant
# (the component carries the model) and ExecutionRoleArn moves up here.
try:
sm.create_endpoint_config(
EndpointConfigName=config_name,
ExecutionRoleArn=role_arn,
ProductionVariants=[variant],
Tags=tags,
)
except ClientError as e:
if "Cannot create already existing endpoint configuration" in str(e):
log(f"Endpoint config {config_name} already exists — reusing")
else:
raise
return config_name
def create_endpoint(sm: Any, *, endpoint_name: str, config_name: str, tags: list[dict]) -> None:
log(f"Creating endpoint: {endpoint_name}")
sm.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=config_name,
Tags=tags,
)
def create_inference_component(
sm: Any, *, ic_name: str, endpoint_name: str, model_name: str,
accelerator_devices: int, min_memory_mb: int, tags: list[dict],
) -> None:
log(f"Creating inference component: {ic_name}")
sm.create_inference_component(
InferenceComponentName=ic_name,
EndpointName=endpoint_name,
VariantName="AllTraffic",
Specification={
"ModelName": model_name,
"StartupParameters": {
"ModelDataDownloadTimeoutInSeconds": DEFAULTS["model_data_download_timeout"],
"ContainerStartupHealthCheckTimeoutInSeconds": DEFAULTS["container_startup_timeout"],
},
"ComputeResourceRequirements": {
"MinMemoryRequiredInMb": min_memory_mb,
"NumberOfAcceleratorDevicesRequired": accelerator_devices,
},
},
RuntimeConfig={"CopyCount": 1},
Tags=tags,
)
def scan_component_logs(ic_name: str, region: str, limit: int = 200) -> list[str]:
"""Return crash-marker lines from the component's newest log stream.
Returns [] when the log group does not exist yet, or when the caller cannot
read it. A diagnostic that is unavailable never blocks the deployment.
"""
logs = boto3.client("logs", region_name=region)
group = f"/aws/sagemaker/InferenceComponents/{ic_name}"
try:
streams = logs.describe_log_streams(
logGroupName=group, orderBy="LastEventTime", descending=True, limit=1
)["logStreams"]
except ClientError:
return []
if not streams:
return []
try:
events = logs.get_log_events(
logGroupName=group,
logStreamName=streams[0]["logStreamName"],
limit=limit,
startFromHead=False,
)["events"]
except ClientError:
return []
return [
event["message"].strip()[:500]
for event in events
if any(marker in event["message"] for marker in CRASH_MARKERS)
]
def wait_for_component(sm: Any, ic_name: str, region: str, timeout_minutes: int = 30) -> None:
"""Poll DescribeInferenceComponent until InService.
Also scans the container log on every poll. A crash loop never changes the
component status — it stays Creating until the startup timeout expires — so
the log is the only early signal.
"""
log(f"Waiting for inference component {ic_name} (up to {timeout_minutes} min)...")
start = time.time()
deadline = start + timeout_minutes * 60
polls = 0
while time.time() < deadline:
desc = sm.describe_inference_component(InferenceComponentName=ic_name)
status = desc["InferenceComponentStatus"]
elapsed = int(time.time() - start)
if status == "InService":
log(f"Component InService after {elapsed}s")
return
if status == "Failed":
reason = desc.get("FailureReason", "(no reason given)")
raise RuntimeError(f"Inference component failed after {elapsed}s: {reason}")
polls += 1
log(f" status={status} elapsed={elapsed}s")
# One grace poll: the first seconds of any boot look noisy.
if polls >= 2:
hits = scan_component_logs(ic_name, region)
if hits:
log("Container is crash-looping. Log evidence:")
for line in hits[-6:]:
log(f" {line}")
raise RuntimeError(
"Container does not stay up. Fix the container error above; "
"the component status alone would have hidden this for "
f"{DEFAULTS['container_startup_timeout']}s."
)
time.sleep(30)
raise TimeoutError(f"Component did not reach InService within {timeout_minutes} minutes")
def register_autoscaling(
*, ic_name: str, min_copies: int, max_copies: int, concurrency_target: int,
region: str,
) -> str:
"""Register the scalable target and both policies. Returns the step ARN.
Two policies, both required:
1. target tracking on concurrency per copy — scales 1..n, and its idle
zeros are what take the count down to zero
2. step scaling — the only way out of zero, since target tracking cannot
divide by zero copies
"""
log(f"Registering component autoscaling: copies={min_copies}-{max_copies} "
f"concurrency-target={concurrency_target}/copy")
appscaling = boto3.client("application-autoscaling", region_name=region)
resource_id = f"inference-component/{ic_name}"
appscaling.register_scalable_target(
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension=IC_DIMENSION,
MinCapacity=min_copies,
MaxCapacity=max_copies,
)
appscaling.put_scaling_policy(
PolicyName=f"{ic_name}-concurrency-target-tracking",
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension=IC_DIMENSION,
PolicyType="TargetTrackingScaling",
TargetTrackingScalingPolicyConfiguration={
"TargetValue": float(concurrency_target),
"PredefinedMetricSpecification": {"PredefinedMetricType": CONCURRENCY_METRIC},
"ScaleInCooldown": DEFAULTS["scale_in_cooldown_seconds"],
"ScaleOutCooldown": DEFAULTS["scale_out_cooldown_seconds"],
},
)
resp = appscaling.put_scaling_policy(
PolicyName=f"{ic_name}-step-wake-from-zero",
ServiceNamespace="sagemaker",
ResourceId=resource_id,
ScalableDimension=IC_DIMENSION,
PolicyType="StepScaling",
StepScalingPolicyConfiguration={
"AdjustmentType": "ChangeInCapacity",
"MetricAggregationType": "Maximum",
"Cooldown": DEFAULTS["wake_cooldown_seconds"],
"StepAdjustments": [
{"MetricIntervalLowerBound": 0, "ScalingAdjustment": DEFAULTS["wake_step_size"]},
],
},
)
return resp["PolicyARN"]
def create_alarms(
*, ic_name: str, endpoint_name: str, step_policy_arn: str,
sns_topic_arn: str | None, region: str,
) -> None:
"""Wake alarm (drives the step policy) plus an error alarm."""
cw = boto3.client("cloudwatch", region_name=region)
# The wake alarm's action is the step policy, never an SNS topic. Period 30
# with one datapoint keeps the wake latency near a minute.
log(f"Creating wake alarm: {ic_name}-wake-from-zero")
cw.put_metric_alarm(
AlarmName=f"{ic_name}-wake-from-zero",
AlarmDescription="Component invoked with zero copies — wake from zero",
AlarmActions=[step_policy_arn],
MetricName=WAKE_METRIC,
Namespace="AWS/SageMaker",
Statistic="Maximum",
Dimensions=[{"Name": "InferenceComponentName", "Value": ic_name}],
Period=30,
EvaluationPeriods=1,
DatapointsToAlarm=1,
Threshold=1,
ComparisonOperator="GreaterThanOrEqualToThreshold",
TreatMissingData="missing",
)
alarm_actions = [sns_topic_arn] if sns_topic_arn else []
cw.put_metric_alarm(
AlarmName=f"{endpoint_name}-Invocation5XXErrors",
AlarmDescription="5XX errors > 5 in 5min",
AlarmActions=alarm_actions,
MetricName="Invocation5XXErrors",
Namespace="AWS/SageMaker",
Statistic="Sum",
Dimensions=[
{"Name": "EndpointName", "Value": endpoint_name},
{"Name": "VariantName", "Value": "AllTraffic"},
],
Period=DEFAULTS["alarm_period_seconds"],
EvaluationPeriods=DEFAULTS["alarm_evaluation_periods"],
Threshold=DEFAULTS["alarm_5xx_threshold_count"],
ComparisonOperator="GreaterThanThreshold",
TreatMissingData="notBreaching",
)
if not sns_topic_arn:
log("WARNING: no --sns-alarm-topic — the error alarm won't notify anyone.")
def main() -> int:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
# Required
p.add_argument("--model-name", required=True)
p.add_argument("--image-uri", required=True, help="From serving-image-selection")
p.add_argument("--role-arn", required=True, help="From sagemaker-iam-preflight")
p.add_argument("--instance-type", required=True, help="e.g. ml.g5.xlarge")
p.add_argument("--region", required=True, help="From aws-context-discovery")
# Conditional
p.add_argument("--model-s3-uri", default=None,
help="Pre-staged weights. Strongly recommended here: they are "
"re-downloaded on every wake from zero.")
p.add_argument("--env", action="append", default=[], help="KEY=VALUE; repeatable")
p.add_argument("--inference-ami-version", default=None,
help="REQUIRED for vLLM DLC with CUDA 13+ "
"(al2-ami-sagemaker-inference-gpu-3-1)")
# Naming
p.add_argument("--endpoint-name", default=None, help="Default: <model-name>-<timestamp>")
p.add_argument("--inference-component-name", default=None, help="Default: <model-name>-ic")
p.add_argument("--project", default=None, help="Tag value (default: model name)")
p.add_argument("--environment", default=DEFAULTS["environment_tag"])
# Capacity
p.add_argument("--initial-instance-count", type=int, default=DEFAULTS["initial_instance_count"])
p.add_argument("--min-instance-count", type=int, default=DEFAULTS["min_instance_count"],
help="0 enables scale-to-zero. Anything else defeats the point.")
p.add_argument("--max-instance-count", type=int, default=DEFAULTS["max_instance_count"])
p.add_argument("--min-copy-count", type=int, default=DEFAULTS["min_copy_count"])
p.add_argument("--max-copy-count", type=int, default=DEFAULTS["max_copy_count"])
p.add_argument("--concurrency-target-per-copy", type=int,
default=DEFAULTS["concurrency_target_per_copy"])
# Component resources
p.add_argument("--accelerator-devices", type=int, default=DEFAULTS["accelerator_devices"],
help="Must match SM_VLLM_TENSOR_PARALLEL_SIZE for multi-GPU models")
p.add_argument("--min-memory-mb", type=int, default=DEFAULTS["min_memory_required_mb"])
# Alarms
p.add_argument("--sns-alarm-topic", default=None, help="SNS topic ARN for the error alarm")
p.add_argument("--no-alarms", action="store_true",
help="NOT RECOMMENDED: without the wake alarm the endpoint never leaves zero")
p.add_argument("--no-autoscaling", action="store_true",
help="NOT RECOMMENDED: creates the endpoint without any scaling")
args = p.parse_args()
env_dict = parse_env(args.env)
endpoint_name = make_endpoint_name(args.model_name, args.endpoint_name)
config_name = f"{endpoint_name}-config"
ic_name = args.inference_component_name or f"{args.model_name.replace('_', '-').lower()}-ic"[:63]
sts = boto3.client("sts", region_name=args.region)
sm = boto3.client("sagemaker", region_name=args.region)
identity = sts.get_caller_identity()
if args.min_instance_count != 0:
log(f"NOTE: --min-instance-count {args.min_instance_count} — this endpoint "
"will NOT scale to zero instances.")
tags = build_tags(
project=args.project or args.model_name,
caller_arn=identity["Arn"],
environment=args.environment,
model_s3_uri=args.model_s3_uri,
extra={"InferenceMode": "realtime-ic-scale-to-zero"},
)
create_model(
sm, model_name=args.model_name, image_uri=args.image_uri,
role_arn=args.role_arn, model_s3_uri=args.model_s3_uri,
env=env_dict, tags=tags, log_prefix="deploy_ic",
)
create_endpoint_config(
sm, config_name=config_name, instance_type=args.instance_type,
role_arn=args.role_arn, initial_instance_count=args.initial_instance_count,
min_instance_count=args.min_instance_count,
max_instance_count=args.max_instance_count,
inference_ami_version=args.inference_ami_version, tags=tags,
)
create_endpoint(sm, endpoint_name=endpoint_name, config_name=config_name, tags=tags)
# An IC endpoint starts empty, so this is fast (~4 min): no model loads yet.
wait_for_endpoint(sm, endpoint_name, log_prefix="deploy_ic")
create_inference_component(
sm, ic_name=ic_name, endpoint_name=endpoint_name, model_name=args.model_name,
accelerator_devices=args.accelerator_devices, min_memory_mb=args.min_memory_mb,
tags=tags,
)
wait_for_component(sm, ic_name, args.region)
step_policy_arn = None
if not args.no_autoscaling:
step_policy_arn = register_autoscaling(
ic_name=ic_name, min_copies=args.min_copy_count,
max_copies=args.max_copy_count,
concurrency_target=args.concurrency_target_per_copy, region=args.region,
)
else:
log("WARNING: autoscaling skipped. This endpoint will not scale at all.")
if not args.no_alarms and step_policy_arn:
create_alarms(
ic_name=ic_name, endpoint_name=endpoint_name,
step_policy_arn=step_policy_arn, sns_topic_arn=args.sns_alarm_topic,
region=args.region,
)
elif not args.no_alarms:
log("WARNING: no step policy, so no wake alarm. Nothing wakes this endpoint.")
# Summary
log("")
log(f"Deployment complete: {endpoint_name}")
log(f" Component: {ic_name}")
log(f" Instance: {args.instance_type} "
f"({args.min_instance_count}-{args.max_instance_count})")
log(f" Copies: {args.min_copy_count}-{args.max_copy_count}")
log(f" Scale to zero: {'YES' if args.min_instance_count == 0 and args.min_copy_count == 0 else 'NO'}")
log("")
log("Idle behaviour: copies reach 0 after ~11 min without traffic, instances")
log("~12 min later. The first request after that returns a 400 and wakes the")
log("endpoint; a 200 follows about 9 min later (Hub download included).")
log("")
log(f"Test: python3 invoke_endpoint.py --endpoint-name {endpoint_name} \\")
log(f" --inference-component-name {ic_name} \\")
log(" --payload '{\"prompt\": \"hello\", \"max_tokens\": 16}' \\")
log(f" --wait-for-capacity 900 --region {args.region}")
log(f"Teardown: python3 teardown.py {endpoint_name} {args.region}")
print(json.dumps({
"endpoint_name": endpoint_name,
"endpoint_config_name": config_name,
"model_name": args.model_name,
"inference_component_name": ic_name,
"step_policy_arn": step_policy_arn,
"region": args.region,
"instance_type": args.instance_type,
"scales_to_zero": args.min_instance_count == 0 and args.min_copy_count == 0,
}))
return 0
if __name__ == "__main__":
sys.exit(main())
invoke_endpoint.py 6.4 KB
#!/usr/bin/env python3
"""Invoke a real-time SageMaker endpoint with a JSON payload. Cross-platform.
This is the BOM-safe way to test an endpoint. On Windows, writing a payload with
PowerShell's `Set-Content -Encoding UTF8` can prepend a UTF-8 byte-order mark
(BOM). SageMaker's JSON parser rejects it with:
Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
This helper never produces that error: it reads the payload with `utf-8-sig`
(stripping any BOM the source file may already have) and writes the request body
as plain BOM-free UTF-8 before calling `aws sagemaker-runtime invoke-endpoint`.
Usage:
python invoke_endpoint.py --endpoint-name NAME --payload '{"inputs": "hi"}'
python invoke_endpoint.py --endpoint-name NAME --payload-file body.json
python invoke_endpoint.py --endpoint-name NAME --payload-file img.json \\
--content-type application/json --region eu-west-1
Inference-component endpoints (including scale-to-zero deployments) need the
component name, and a cold endpoint needs a wait:
python invoke_endpoint.py --endpoint-name NAME \\
--inference-component-name COMP --payload '{"prompt": "hi"}' \\
--wait-for-capacity 900
A component scaled to zero copies answers the first request with a 400
ValidationError ("has no capacity"). That error is also the wake signal: it
publishes NoCapacityInvocationFailures, which triggers the step-scaling policy.
With --wait-for-capacity the helper keeps retrying until a copy is in service.
The endpoint response body is printed to stdout.
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
NO_CAPACITY_MARKERS = ("has no capacity", "NoCapacity")
def log(msg: str) -> None:
print(f"[invoke] {msg}", file=sys.stderr, flush=True)
def aws_bin() -> str:
exe = shutil.which("aws")
if not exe:
log("ERROR: the 'aws' CLI was not found on PATH. Install AWS CLI v2.")
sys.exit(2)
return exe
def resolve_region(arg_region: str | None) -> str:
if arg_region:
return arg_region
for var in ("AWS_REGION", "AWS_DEFAULT_REGION"):
if os.environ.get(var):
return os.environ[var]
proc = subprocess.run(
[aws_bin(), "configure", "get", "region"], capture_output=True, text=True
)
return proc.stdout.strip() if proc.returncode == 0 else ""
def load_payload(args: argparse.Namespace) -> str:
"""Return the raw payload text, BOM stripped. Validates JSON when applicable."""
if args.payload_file:
# utf-8-sig decodes and discards a leading BOM if the file has one.
raw = open(args.payload_file, "r", encoding="utf-8-sig").read()
else:
raw = args.payload
# If it's meant to be JSON, validate and re-serialize so the body is clean.
if "json" in args.content_type:
try:
return json.dumps(json.loads(raw))
except json.JSONDecodeError as e:
log(f"ERROR: payload is not valid JSON: {e}")
sys.exit(1)
return raw
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--endpoint-name", required=True)
parser.add_argument("--region")
parser.add_argument("--content-type", default="application/json")
parser.add_argument(
"--inference-component-name",
help="Required when the endpoint hosts inference components",
)
parser.add_argument(
"--wait-for-capacity", type=int, default=0, metavar="SECONDS",
help=(
"Retry while the component reports no capacity (scale-to-zero wake). "
"0 fails immediately."
),
)
src = parser.add_mutually_exclusive_group(required=True)
src.add_argument("--payload", help="Inline request body (e.g. a JSON string)")
src.add_argument("--payload-file", help="Path to a file containing the request body")
args = parser.parse_args()
region = resolve_region(args.region)
if not region:
log("ERROR: no AWS region. Pass --region or set AWS_REGION.")
return 1
body = load_payload(args)
# Write the request body as BOM-free UTF-8. NamedTemporaryFile + explicit
# utf-8 encoding guarantees no BOM regardless of platform.
body_path = None
out_path = None
try:
with tempfile.NamedTemporaryFile(
"w", suffix=".json", encoding="utf-8", delete=False
) as f:
f.write(body)
body_path = f.name
out_fd, out_path = tempfile.mkstemp(suffix=".out")
os.close(out_fd)
cmd = [
aws_bin(), "sagemaker-runtime", "invoke-endpoint",
"--endpoint-name", args.endpoint_name,
"--content-type", args.content_type,
"--body", f"fileb://{body_path}",
"--region", region,
]
if args.inference_component_name:
cmd += ["--inference-component-name", args.inference_component_name]
cmd.append(out_path)
log(f"Invoking {args.endpoint_name} in {region}...")
deadline = time.time() + args.wait_for_capacity
attempt = 0
while True:
attempt += 1
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode == 0:
break
err = proc.stderr.strip()
no_capacity = any(marker in err for marker in NO_CAPACITY_MARKERS)
if no_capacity and time.time() < deadline:
if attempt == 1:
log("No capacity: the component is at zero copies. "
"This request triggered the wake alarm; retrying.")
log(f" attempt {attempt}: still no capacity, waiting 30s "
f"({int(deadline - time.time())}s left)")
time.sleep(30)
continue
log("Invocation failed:")
log(err)
if no_capacity:
log("HINT: the component has no copies in service. Pass "
"--wait-for-capacity 900 to wait for the wake-from-zero policy.")
return 1
# The response body landed in out_path; print it to stdout.
print(open(out_path, "r", encoding="utf-8-sig").read())
return 0
finally:
for p in (body_path, out_path):
if p and os.path.exists(p):
os.remove(p)
if __name__ == "__main__":
sys.exit(main())
teardown.py 9.2 KB
#!/usr/bin/env python3
"""Tear down a SageMaker endpoint and its associated resources. Cross-platform.
Deletes in safe order: alarms -> autoscaling -> inference components ->
endpoint (stops billing) -> endpoint config -> model.
Handles both deployment shapes:
- model-based endpoints (deploy.py, deploy_async.py): the variant carries the
model, autoscaling targets endpoint/<name>/variant/AllTraffic
- inference-component endpoints (deploy_ic.py, scale-to-zero): the component
carries the model, autoscaling targets inference-component/<name>
Does NOT delete: IAM role, data capture S3 objects, SNS topic, model artifacts.
Idempotent — missing resources are skipped, not errors.
Calls the `aws` CLI from the current shell, so it inherits the same AWS context
(profile, region, SSO session) — no Bash/WSL context-sharing problem on Windows.
Usage:
python teardown.py <endpoint-name> [<region>]
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import time
VARIANT_DIM = "sagemaker:variant:DesiredInstanceCount"
IC_DIM = "sagemaker:inference-component:DesiredCopyCount"
def log(msg: str) -> None:
print(f"[teardown] {msg}", file=sys.stderr, flush=True)
def aws_bin() -> str:
exe = shutil.which("aws")
if not exe:
log("ERROR: the 'aws' CLI was not found on PATH. Install AWS CLI v2.")
sys.exit(2)
return exe
def run_aws(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run([aws_bin(), *args], capture_output=True, text=True)
def json_out(proc: subprocess.CompletedProcess, default):
if proc.returncode != 0:
return default
try:
return json.loads(proc.stdout) or default
except json.JSONDecodeError:
return default
def resolve_region(arg_region: str | None) -> str:
"""Region from arg, then env, then the active profile's config."""
if arg_region:
return arg_region
for var in ("AWS_REGION", "AWS_DEFAULT_REGION"):
if os.environ.get(var):
return os.environ[var]
proc = run_aws(["configure", "get", "region"])
return proc.stdout.strip() if proc.returncode == 0 else ""
def delete_alarms(prefix: str, reg: list[str]) -> None:
alarms = json_out(
run_aws(["cloudwatch", "describe-alarms", "--alarm-name-prefix", prefix,
"--query", "MetricAlarms[*].AlarmName", "--output", "json", *reg]),
[],
)
if alarms:
run_aws(["cloudwatch", "delete-alarms", "--alarm-names", *alarms, *reg])
log(f"Deleted alarms: {' '.join(alarms)}")
def delete_scaling_stack(resource_id: str, dimension: str, reg: list[str]) -> None:
"""Delete every scaling policy on a target, then deregister the target."""
policies = json_out(
run_aws(["application-autoscaling", "describe-scaling-policies",
"--service-namespace", "sagemaker", "--resource-id", resource_id,
"--query", "ScalingPolicies[*].PolicyName", "--output", "json", *reg]),
[],
)
for policy in policies:
run_aws(["application-autoscaling", "delete-scaling-policy",
"--service-namespace", "sagemaker", "--resource-id", resource_id,
"--scalable-dimension", dimension, "--policy-name", policy, *reg])
log(f"Deleted autoscaling policy: {policy}")
targets = json_out(
run_aws(["application-autoscaling", "describe-scalable-targets",
"--service-namespace", "sagemaker", "--resource-ids", resource_id,
"--query", "ScalableTargets[*].ResourceId", "--output", "json", *reg]),
[],
)
if resource_id in targets:
run_aws(["application-autoscaling", "deregister-scalable-target",
"--service-namespace", "sagemaker", "--resource-id", resource_id,
"--scalable-dimension", dimension, *reg])
log(f"Deregistered scalable target: {resource_id}")
def list_inference_components(endpoint_name: str, reg: list[str]) -> list[str]:
return json_out(
run_aws(["sagemaker", "list-inference-components",
"--endpoint-name-equals", endpoint_name,
"--query", "InferenceComponents[*].InferenceComponentName",
"--output", "json", *reg]),
[],
)
def component_model_name(ic_name: str, reg: list[str]) -> str:
desc = json_out(
run_aws(["sagemaker", "describe-inference-component",
"--inference-component-name", ic_name, *reg]),
{},
)
return desc.get("Specification", {}).get("ModelName", "")
def delete_inference_components(ic_names: list[str], reg: list[str],
timeout_seconds: int = 900) -> None:
"""Delete components and wait until they are gone.
Retries the delete on every poll, because SageMaker refuses it in two
transient states seen in practice:
- CREATE_IN_PROGRESS (container still starting)
- UPDATE_RC_IN_PROGRESS (a scaling action is changing the copy count)
An adapter component must also go before its base component, and the
ordering falls out of the same retry loop.
"""
pending = list(ic_names)
deadline = time.time() + timeout_seconds
announced: set[str] = set()
while pending and time.time() < deadline:
for ic_name in pending:
if ic_name not in announced:
log(f"Deleting inference component: {ic_name}")
announced.add(ic_name)
run_aws(["sagemaker", "delete-inference-component",
"--inference-component-name", ic_name, *reg])
still_there = [
ic_name for ic_name in pending
if run_aws(["sagemaker", "describe-inference-component",
"--inference-component-name", ic_name, *reg]).returncode == 0
]
pending = still_there
if pending:
time.sleep(15)
if pending:
log(f"WARNING: components still present after {timeout_seconds}s: {' '.join(pending)}")
else:
log("All inference components deleted")
def main() -> int:
if len(sys.argv) < 2:
log(f"Usage: {os.path.basename(sys.argv[0])} <endpoint-name> [<region>]")
return 64
endpoint_name = sys.argv[1]
region = resolve_region(sys.argv[2] if len(sys.argv) > 2 else None)
if not region:
log("ERROR: no AWS region. Pass region as 2nd arg or set AWS_REGION.")
return 1
reg = ["--region", region]
log(f"Tearing down endpoint: {endpoint_name} in {region}")
# Discover what's attached to this endpoint.
config_name = ""
model_names: list[str] = []
desc = run_aws(["sagemaker", "describe-endpoint", "--endpoint-name", endpoint_name, *reg])
endpoint_exists = desc.returncode == 0
if endpoint_exists:
config_name = json_out(desc, {}).get("EndpointConfigName", "")
else:
log("Endpoint not found — checking for orphan resources anyway")
if config_name:
cfg = json_out(
run_aws(["sagemaker", "describe-endpoint-config",
"--endpoint-config-name", config_name, *reg]),
{},
)
# Model-based endpoints name the model on the variant. IC-based ones do not.
for variant in cfg.get("ProductionVariants", []):
if variant.get("ModelName"):
model_names.append(variant["ModelName"])
ic_names = list_inference_components(endpoint_name, reg)
if ic_names:
log(f"Inference components on this endpoint: {' '.join(ic_names)}")
for ic_name in ic_names:
model = component_model_name(ic_name, reg)
if model and model not in model_names:
model_names.append(model)
# Alarms — discovered by name prefix. deploy.py / deploy_async.py name them
# "<endpoint>-*"; deploy_ic.py names the wake alarm "<component>-*".
delete_alarms(f"{endpoint_name}-", reg)
for ic_name in ic_names:
delete_alarms(f"{ic_name}-", reg)
# Autoscaling — variant target (model-based) and component targets (IC-based).
delete_scaling_stack(f"endpoint/{endpoint_name}/variant/AllTraffic", VARIANT_DIM, reg)
for ic_name in ic_names:
delete_scaling_stack(f"inference-component/{ic_name}", IC_DIM, reg)
# Inference components must go before the endpoint.
if ic_names:
delete_inference_components(ic_names, reg)
# Endpoint (stops billing)
if endpoint_exists:
run_aws(["sagemaker", "delete-endpoint", "--endpoint-name", endpoint_name, *reg])
log(f"Deleted endpoint: {endpoint_name} (billing stopped)")
# Endpoint config
if config_name and run_aws(
["sagemaker", "describe-endpoint-config", "--endpoint-config-name", config_name, *reg]
).returncode == 0:
run_aws(["sagemaker", "delete-endpoint-config", "--endpoint-config-name", config_name, *reg])
log(f"Deleted endpoint config: {config_name}")
# Models
for model_name in model_names:
if run_aws(["sagemaker", "describe-model", "--model-name", model_name, *reg]).returncode == 0:
run_aws(["sagemaker", "delete-model", "--model-name", model_name, *reg])
log(f"Deleted model: {model_name}")
log("Teardown complete. Data capture S3 objects (if any) NOT deleted — manage separately.")
return 0
if __name__ == "__main__":
sys.exit(main())
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/huggingface/skills/blob/main/LICENSE