AWS微调示例:合成测试满分,手写测试仍有错
AWS演示从工单日志发现新类别、规则重标注、微调及并行部署。调整后280条同生成器留出样本全部答对,另写的24条测试只答对20条,暴露了关键词捷径;模型自报置信度也未经校准。
提供可复用的漂移诊断与评测方法。已核对署名全文及原站精确发布时间;使用合成数据,类别扩充与微调同时发生,提升不能全部归于微调,尚未独立复测。
部署在 Amazon SageMaker HyperPod 上的基础模型会遇到任何预先整理的数据集都无法覆盖的输入,包括领域专用术语、意外的格式、新产品以及不断变化的用户行为。如果没有生产环境推理数据的记录,团队就无法检测漂移、发现故障模式,也无法利用真实交互改进模型。
Amazon SageMaker HyperPod 现已提供 Data Capture,这项内置功能可在三个相互独立的层级将实时推理输入和输出记录到 Amazon Simple Storage Service(Amazon S3),对延迟的影响极小,对模型可用性完全没有影响。
本文将演示一个在单个 SageMaker HyperPod 集群上运行的完整示例。家电支持工单路由器捕获生产流量,Amazon Athena 查询揭示新产品带来的识别盲区,SQL 策略为捕获的记录打标签,再利用这些数据进行微调,让路由器学会识别新产品。我们使用模型部署之前不可能存在的数据,衡量微调前后的准确率。推理操作器在一个节点上提供模型服务,训练操作器在另一个节点上执行微调。
本演示使用合成数据。脚本、清单文件、SQL、合成数据集和预期输出均可在配套 GitHub 仓库中找到。
三层 Data Capture 架构
HyperPod Data Capture 提供三个相互独立的层级,分别位于请求路径的不同位置。你可以在同一个 dataCapture 配置块中启用任意组合。
| 第 1 层,SageMaker 端点 | 第 2 层,负载均衡器 | 第 3 层,模型 Pod | |
| 捕获内容 | 完整的请求和响应载荷 | Application Load Balancer(ALB)访问日志字段,包括请求行、状态码、耗时、客户端 IP、用户代理 | 完整的请求和响应载荷,以及事件元数据 |
| 管理方式 | SageMaker 原生数据捕获 | ALB 访问日志 | HyperPod 推理操作器(NGINX + OTel 收集器 + S3 上传器边车容器) |
| 最适合的用途 | 合规、Model Monitor、审计 | 低成本监控流量和错误率 | 调试、分析、训练数据收集 |
| 配置 | sagemakerEndpoint:,采样百分比、输入/输出、AWS KMS |
loadBalancer: { enabled: true } |
modelPod:,采样百分比、输入/输出、缓冲区、最大载荷大小、AWS KMS、内容类型 |
第 1 层和第 3 层都会存储完整载荷,因此同时启用这两层会让每条记录存储两次。合规和 Model Monitor 场景使用第 1 层,只需要流量元数据时使用第 2 层,打算使用载荷时使用第 3 层。本文仅使用第 3 层。由于第 3 层会记录完整载荷,其中可能包含姓名、地址和订单号,因此在将这些数据用作训练数据之前,应先做好保护。可采用采样、AWS Key Management Service(AWS KMS)加密(kmsKeyId)、S3 生命周期规则,以及个人身份信息(PII)脱敏,例如使用 Amazon Comprehend。
前提条件
- 一个由 Amazon Elastic Kubernetes Service(Amazon EKS)编排的 SageMaker HyperPod 集群,已安装推理操作器(设置用于模型部署的 HyperPod 集群),并已安装训练操作器 EKS 附加组件
amazon-sagemaker-hyperpod-training-operator(安装训练操作器)。 - 两块可用的 NVIDIA GPU,一块用于提供服务,一块用于训练。我们使用
ml.g6e.8xlarge提供服务,使用ml.g6e.xlarge进行训练,两者各配备一块 48 GB NVIDIA L40S。服务 Pod 会在端点的整个生命周期内占用其 GPU,因此如果只有一块 GPU,训练 Pod 就会一直处于Pending状态。 - 已为集群配置
kubectl。 - 同一区域中的一个 S3 存储桶。
确认两个操作器均已安装。该命令会返回两行结果。
kubectl get crd | grep -E 'inferenceendpointconfigs|hyperpodpytorchjobs'
hyperpodpytorchjobs.sagemaker.amazonaws.com 2026-09-21T10:57:14Z
inferenceendpointconfigs.inference.sagemaker.aws.amazon.com 2026-08-06T11:58:53Z解决方案概览
下图展示了在一个 SageMaker HyperPod 集群上完成演示的五个步骤,将每次请求和响应捕获到 Amazon S3,使用 Athena 分析捕获数据,通过 SQL 策略打标签,使用训练操作器在第二块 GPU 上进行微调,并在保持捕获开启的情况下并行重新部署。
图 1,单个 SageMaker HyperPod 集群上的五步飞轮,从捕获开始,依次经过 Athena 分析、打标签、微调和重新部署
推理操作器会向模型 Pod 添加三个边车容器。每个经过 NGINX 代理的请求都会被复制到 OpenTelemetry 收集器,经过批处理后,通过 Mountpoint-S3 卷写入 S3。Athena 会直接读取这些文件。训练操作器在第二块 GPU 上以 HyperPodPyTorchJob 的形式运行微调,新模型则由第二个同样启用了捕获的端点提供服务。
第 0 步,设置变量
后续所有步骤都会读取这些变量。编辑第一个代码块,然后粘贴整段内容。
# --- edit these ---
export EKS_CLUSTER_NAME="my-hyperpod-eks"
export AWS_REGION="us-east-1"
export BUCKET="amzn-s3-demo-bucket"
export SERVE_INSTANCE_TYPE="ml.g6e.8xlarge" # node type for the first endpoint
export TRAIN_INSTANCE_TYPE="ml.g6e.xlarge" # node type for the fine-tuning job
# --- leave as-is ---
export AWS_DEFAULT_REGION="$AWS_REGION"
export ENDPOINT_NAME="appliance-router"
export MODEL_LOCATION="models/qwen2.5-3b-instruct"
export MODEL_V2_LOCATION="models/qwen2.5-3b-router-v2"
export TRAIN_SA="flywheel" # service account with S3 access via EKS Pod Identity
aws eks update-kubeconfig --name "$EKS_CLUSTER_NAME" --region "$AWS_REGION"
render() { python3 -c 'import os,sys; sys.stdout.write(os.path.expandvars(sys.stdin.read()))'; }第 1 步,将基础模型暂存到 S3
我们使用 Qwen2.5-3B-Instruct,因为它足够小,大约一分钟就能完成微调,而且单块 L40S 就能容纳。
pip install -q huggingface_hub
python3 -c "from huggingface_hub import snapshot_download; \
snapshot_download('Qwen/Qwen2.5-3B-Instruct', local_dir='qwen2.5-3b-instruct')"
aws s3 sync qwen2.5-3b-instruct "s3://${BUCKET}/${MODEL_LOCATION}/" --exclude ".cache/*"第 2 步,IAM 权限
四个身份需要访问权限。策略语句请参阅 HyperPod 上的推理数据捕获。
- Mountpoint-S3 CSI 驱动程序角色。第 3 层捕获通过 Mountpoint-S3 卷写入数据,驱动程序使用其自身的服务账户 IAM 角色(IRSA)进行身份验证,而非 Pod 的服务账户。它需要对捕获存储桶拥有
s3:PutObject、s3:AbortMultipartUpload和s3:DeleteObject权限,如果设置了kmsKeyId,还需要kms:Decrypt、kms:GenerateDataKey和kms:DescribeKey权限。如果缺少这些权限,端点仍会保持健康,请求也能成功,但不会出现任何捕获数据。请参阅 Mountpoint for Amazon S3 CSI 驱动程序。 - 推理操作器执行角色。它需要对捕获存储桶拥有
s3:PutObject权限,如果设置了kmsKeyId,还需要kms:Decrypt和kms:GenerateDataKey权限。捕获文件本身通过 CSI 驱动程序角色写入,因此如果没有出现捕获数据,应先检查该角色。 - 训练 Pod 的服务账户(
$TRAIN_SA)。通过 EKS Pod Identity 获得对基础模型和训练数据的读取权限,以及对合并后模型的写入权限。 - Athena。对捕获前缀的读取权限,以及一个查询结果存储位置。
启用 Data Capture
接下来的三个步骤将部署启用了第 3 层捕获的路由器,检查 Pod 是否运行捕获边车容器,并确认记录已到达 Amazon S3。
第 3 步,部署启用了第 3 层捕获的模型
整个功能的配置就是这个 dataCapture.modelPod.enabled: true 配置块。其余部分都是普通的 vLLM 部署。
cat > endpoint.yaml <<'YAML'
apiVersion: inference.sagemaker.aws.amazon.com/v1
kind: InferenceEndpointConfig
metadata:
name: ${ENDPOINT_NAME}
namespace: default
spec:
replicas: 1
modelName: ${ENDPOINT_NAME}
endpointName: ${ENDPOINT_NAME}
instanceType: ${SERVE_INSTANCE_TYPE}
invocationEndpoint: v1/chat/completions
modelSourceConfig:
modelSourceType: s3
modelLocation: ${MODEL_LOCATION}
s3Storage:
bucketName: ${BUCKET}
region: ${AWS_REGION}
# >>> This is all you need to turn on Tier 3 data capture <<<
dataCapture:
s3Uri: "s3://${BUCKET}/capture/"
modelPod:
enabled: true
initialSamplingPercentage: 100
bufferConfig:
batchSize: 50
flushIntervalSeconds: 60
payloadConfig:
maxPayloadSizeKB: 1024
worker:
image: vllm/vllm-openai:v0.10.0
modelInvocationPort:
containerPort: 8000
name: http
modelVolumeMount:
mountPath: /opt/ml/model
name: model-weights
args: ["--model", "/opt/ml/model", "--served-model-name", "${ENDPOINT_NAME}",
"--port", "8000", "--max-model-len", "2048", "--gpu-memory-utilization", "0.90"]
resources:
requests: { cpu: "2", memory: 16Gi, nvidia.com/gpu: 1 }
limits: { nvidia.com/gpu: 1 }
YAML
render < endpoint.yaml | kubectl apply -f -前面的 modelPod 配置块设置了 100% 采样,并同时捕获输入和输出,这些都是默认值。如需调整,可在 modelPod 下添加以下任意可选字段。
modelPod:
enabled: true
initialSamplingPercentage: 50 # capture 50% of requests (default 100)
bufferConfig:
batchSize: 100 # records buffered per upload batch (default 10)
flushIntervalSeconds: 60 # max seconds before a flush (default 60)
payloadConfig:
maxPayloadSizeKB: 1024 # truncate payloads larger than this (default: no limit)
kmsKeyId: "arn:aws:kms:...:key/..." # encrypt captures at rest第 4 步,等待 Pod 就绪
启用了捕获的 Pod 会运行四个容器,分别是模型、sidecar-reverse-proxy(NGINX)、otel-collector 和 s3-uploader。模型容器和 Pod 的 app 标签均以 modelName 命名。
kubectl get pods -l app=$ENDPOINT_NAME -o custom-columns=\
'NAME:.metadata.name,READY:.status.containerStatuses[*].ready,CONTAINERS:.spec.containers[*].name,NODE:.spec.nodeName'
NAME READY CONTAINERS NODE
appliance-router-849f466476-4f5v8 true,true,true,true appliance-router,s3-uploader,sidecar-reverse-proxy,otel-collector hyperpod-i-0f3fe2684afd6a583在我们的运行中,Pod 在执行 kubectl apply 后约五分钟就绪,其中大部分时间用于下载权重。
第 5 步,发送请求并确认捕获数据已写入 S3
通过端口 8081 上的捕获代理发送推理请求,然后在刷新间隔结束后列出捕获前缀下的对象。模型本身监听端口 8000。发送到该端口的请求会绕过代理,不会被捕获。
POD=$(kubectl get pod -l app=$ENDPOINT_NAME -o jsonpath='{.items[0].metadata.name}')
kubectl port-forward "pod/$POD" 18081:8081 >/dev/null 2>&1 &
sleep 5
curl -s http://localhost:18081/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"'"$ENDPOINT_NAME"'","messages":[{"role":"user","content":"my fridge is not cooling"}],"max_tokens":24}'
echo "Waiting for the capture buffer to flush..."; sleep 75
aws s3 ls "s3://${BUCKET}/capture/" --recursive | grep '\.jsonl$' | head
2026-09-28 15:47:14 634356 capture/20e4425092f90c7f/pod/AllTraffic/2026/09/28/15/28-15-47-12-999-ac31d31b-5156-46ad-9ccc-e8a040ab9ab2.jsonl你会在 {s3Uri}/{uniqueID}/pod/{variant}/{YYYY}/{MM}/{DD}/{HH}/ 下看到一个或多个 .jsonl 对象。uniqueID 按端点生成。每行代表一次推理,采用下文所示的 SageMaker 数据捕获格式。
捕获记录的格式
请求体和响应体以 base64 编码形式存储,encoding 字段对此进行了标明,因此读取时需要先进行 base64 解码,再解析 JSON。
{
"captureData": {
"endpointInput": { "observedContentType": "application/json", "mode": "INPUT",
"data": "eyJtb2RlbCI6ICJyb3V0ZXItZnJlc2giLCAidGVtcGVyYXR1cmUiOiAwLCAi...", "encoding": "BASE64" },
"endpointOutput": { "observedContentType": "application/json", "mode": "OUTPUT",
"data": "eyJpZCI6ImNoYXRjbXBsLTctMTc5MDYxMDM2OS4wMDUtMjMxMiIsIm9iamVj...", "encoding": "BASE64" }
},
"eventMetadata": { "eventId": "26859f07-d60b-4683-94aa-d21e7f19e746", "inferenceTime": "2026-09-28T15:46:09Z" },
"eventVersion": "0"
}解码后,endpointInput.data 是客户端发送的请求体,endpointOutput.data 是模型返回的响应体。
场景,支持工单路由器遇到新产品发布
部署的模型是一个家电零售商的支持工单路由器。它使用 vLLM 引导式 JSON 解码,将每张工单分入六个类别之一,即 ProductFridge、ProductWasher、ProductOven、ProductDishwasher、ProductMicrowave,或兜底类别 Other。引导式解码意味着它只能返回一个包含上述某个标签的有效对象。
{"category": "ProductWasher", "confidence": 1}模型部署后,零售商推出了自有空调产品线 Arctis 系列,包括 Arctis 9K、12K、Mini 等型号。路由器没有对应的类别。它无法表示“这是新产品”,只能选择它已知的最接近的标签。除非记录每次请求和响应,否则响应一经返回,相关证据就会消失。
合成流量
我们生成了两个合成数据集。
- 生产流量包含 900 张工单,使用路由器原有的六标签提示词,在 15 分钟内按顺序通过捕获代理回放。前 400 张发生在产品发布前,没有提及空调。其余 500 张中,Arctis 工单的占比从 15% 逐步升至 55%。
- 评估集包含 280 张已标注工单,每类 40 张,包括新增的
ProductAC类别。该评估集按内容留出,使用了流量中从未出现过的故障症状、句式模板和 Arctis 型号名称。
每个生产请求如下所示,系统提示词已简写。
{"model": "appliance-router", "temperature": 0, "max_tokens": 40,
"messages": [{"role": "system", "content": "You are a support-ticket router for a home-appliance retailer. ... category is one of: ProductFridge, ProductWasher, ProductOven, ProductDishwasher, ProductMicrowave, Other. ..."},
{"role": "user", "content": "Hi, our Arctis 12K blows warm air since last week. Order #66759."}],
"guided_json": {"type": "object", "required": ["category", "confidence"],
"properties": {"category": {"enum": ["ProductFridge", "ProductWasher", "ProductOven",
"ProductDishwasher", "ProductMicrowave", "Other"]},
"confidence": {"type": "number"}}}}要回放流量,请克隆配套仓库,生成数据集,并通过捕获代理发送。scripts/pod.sh 会在模型容器内运行客户端,因此无需负载均衡器或 DNS。客户端会打印 Athena 步骤所需的三个时间戳,即 RUN_START、LAUNCH_TS(产品发布后的第一张工单)和 RUN_END。
git clone https://github.com/awslabs/awsome-distributed-ai.git
cd awsome-distributed-ai/examples/use-cases/sagemaker-hyperpod-data-capture-flywheel
(cd data && python3 ../scripts/gen_dataset.py)
scripts/pod.sh $ENDPOINT_NAME drive /tmp/tickets_traffic.jsonl --seconds 900
RUN_START=2026-09-28 15:52:40
sent 100/900
...
LAUNCH_TS=2026-09-28 15:59:20
...
RUN_END=2026-09-28 16:07:40将本次运行打印的三个值导出为环境变量,并等待一个刷新间隔。
export RUN_START="2026-09-28 15:52:40" LAUNCH_TS="2026-09-28 15:59:20" RUN_END="2026-09-28 16:07:40"
sleep 75 # one flush interval使用 Amazon Athena 发现问题
产品发布后,离线基准测试的结果看起来仍然没有变化,因为这些测试固定在过去。只有捕获的生产流量才能反映这种变化。本节展示数据科学家如何使用 Athena 发现问题,整个过程无需预置任何基础设施。
第 6 步,设置变量并配置 Athena 辅助函数
export ATHENA_DB="flywheel_demo"
export ATHENA_OUTPUT="s3://${BUCKET}/athena-results/"
# Each endpoint writes under its own uniqueID. Pick the prefix whose captured requests name this
# endpoint, not whichever prefix sorts first (the Step 15 endpoint adds a second one).
for id in $(aws s3 ls "s3://${BUCKET}/capture/" | awk '/PRE/{print $2}'); do
key=$(aws s3 ls "s3://${BUCKET}/capture/${id}pod/AllTraffic/" --recursive | awk '/\.jsonl$/{print $4; exit}')
[ -n "$key" ] || continue
model=$(aws s3 cp "s3://${BUCKET}/${key}" - 2>/dev/null | head -n 1 | python3 -c 'import sys, json, base64; r = json.loads(sys.stdin.readline()); print(json.loads(base64.b64decode(r["captureData"]["endpointInput"]["data"]))["model"])')
if [ "$model" = "$ENDPOINT_NAME" ]; then export CAPTURE_LOCATION="s3://${BUCKET}/capture/${id}pod/AllTraffic/"; break; fi
done
echo "$CAPTURE_LOCATION" # s3://<bucket>/capture/<uniqueID>/pod/AllTraffic/
# run_athena "<SQL>": runs one statement, prints tab-separated rows, and sets LAST_QID
run_athena() {
local qid st
qid=$(aws athena start-query-execution --query-string "$1" \
--query-execution-context "Database=$ATHENA_DB" \
--result-configuration "OutputLocation=$ATHENA_OUTPUT" \
--output text --query 'QueryExecutionId') || return 1
while :; do
st=$(aws athena get-query-execution --query-execution-id "$qid" \
--output text --query 'QueryExecution.Status.State')
case "$st" in
SUCCEEDED) break ;;
FAILED|CANCELLED) aws athena get-query-execution --query-execution-id "$qid" \
--output text --query 'QueryExecution.Status.StateChangeReason' >&2; return 1 ;;
esac
sleep 2
done
LAST_QID=$qid
aws athena get-query-results --query-execution-id "$qid" \
--output text --query 'ResultSet.Rows[*].Data[*].VarCharValue'
}
run_athena "CREATE DATABASE IF NOT EXISTS ${ATHENA_DB}"第 7 步,向 Athena 声明捕获数据,分为两层
第一层是封装结构。外部表描述每条记录的外层 JSON,而基于 year/month/day/hour 的分区投影将按小时划分的 S3 前缀映射到分区,无需爬网程序或 ADD PARTITION。data 字段被声明为普通字符串,因为它们是 base64 文本。
run_athena "
CREATE EXTERNAL TABLE IF NOT EXISTS inference_captures (
captureData struct<
endpointInput: struct<observedContentType: string, mode: string, data: string, encoding: string>,
endpointOutput: struct<observedContentType: string, mode: string, data: string, encoding: string>
>,
eventMetadata struct<eventId: string, inferenceTime: string>,
eventVersion string
)
PARTITIONED BY (year string, month string, day string, hour string)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION '${CAPTURE_LOCATION}'
TBLPROPERTIES (
'projection.enabled'='true',
'projection.year.type'='integer', 'projection.year.range'='2026,2035',
'projection.month.type'='integer', 'projection.month.range'='1,12', 'projection.month.digits'='2',
'projection.day.type'='integer', 'projection.day.range'='1,31', 'projection.day.digits'='2',
'projection.hour.type'='integer', 'projection.hour.range'='0,23', 'projection.hour.digits'='2',
'storage.location.template'='${CAPTURE_LOCATION}\${year}/\${month}/\${day}/\${hour}/'
)"第二层是一个视图,对每条记录只解码一次。from_utf8(from_base64(...)) 将载荷还原为 JSON。如果缺少这一步,每次提取都会返回 NULL。工单是用户消息(messages[1],因为 messages[0] 是系统提示词)。模型答案是响应 JSON 内部的一个 JSON 字符串,因此需要再次提取。
run_athena "
CREATE OR REPLACE VIEW preds AS
WITH decoded AS (
SELECT CAST(from_iso8601_timestamp(eventMetadata.inferenceTime) AS timestamp) AS ts,
from_utf8(from_base64(captureData.endpointInput.data)) AS req,
from_utf8(from_base64(captureData.endpointOutput.data)) AS resp
FROM inference_captures
WHERE year = '${RUN_START:0:4}' AND month = '${RUN_START:5:2}' AND day = '${RUN_START:8:2}'
)
SELECT ts,
json_extract_scalar(req, '\$.messages[1].content') AS ticket_text,
json_extract_scalar(json_extract_scalar(resp, '\$.choices[0].message.content'), '\$.category') AS predicted_category,
CAST(json_extract_scalar(json_extract_scalar(resp, '\$.choices[0].message.content'), '\$.confidence') AS double) AS confidence
FROM decoded
WHERE ts >= timestamp '${RUN_START}' AND ts < timestamp '${RUN_END}'
"
run_athena "SELECT count(*) AS n, count_if(predicted_category IS NULL) AS unparsed FROM preds"
n unparsed
900 0关于该视图,有两点需要注意。
- 始终按分区筛选。Athena 读取原始 JSON,因此不带分区筛选条件的查询会扫描你曾经捕获的所有对象。该视图将范围筛选为一天,而时间边界将其限制在本次流量运行期间,因为同一个前缀下还存放着第 5 步的请求。
messages[1]假定一条系统消息后紧跟一条用户消息。捕获流量包含客户端实际发送的各种内容,因此对于多轮或少样本请求,需要相应调整提取方式。
第 8 步,类别分布是否在变化?
run_athena "
SELECT date_trunc('minute', ts) AS minute, count(*) AS tickets,
count_if(predicted_category = 'Other') AS other,
round(100.0 * count_if(predicted_category = 'Other') / count(*), 1) AS other_pct
FROM preds GROUP BY 1 ORDER BY 1"
minute tickets other other_pct
2026-09-28 15:52:00.000 20 0 0.0
2026-09-28 15:53:00.000 60 3 5.0
2026-09-28 15:54:00.000 60 4 6.7
2026-09-28 15:55:00.000 60 4 6.7
2026-09-28 15:56:00.000 60 2 3.3
2026-09-28 15:57:00.000 60 1 1.7
2026-09-28 15:58:00.000 60 3 5.0
2026-09-28 15:59:00.000 60 9 15.0
2026-09-28 16:00:00.000 60 17 28.3
2026-09-28 16:01:00.000 60 14 23.3
2026-09-28 16:02:00.000 60 19 31.7
2026-09-28 16:03:00.000 60 21 35.0
2026-09-28 16:04:00.000 60 20 33.3
2026-09-28 16:05:00.000 60 32 53.3
2026-09-28 16:06:00.000 60 28 46.7
2026-09-28 16:07:00.000 40 26 65.0(输出以制表符分隔。这里为了便于阅读进行了对齐。我们的运行将“数周”压缩到了 15 分钟。在生产环境中,应改为按 date_trunc('day', ts) 或 'week' 分桶。)
下图用柱状图表示每分钟被路由到 Other 的工单占比,用折线表示累计占比,并标出了产品发布时间。
图 2,Arctis 发布前后,被路由到 Other 的工单的每分钟占比和累计占比
发布前,Other 的每分钟占比始终低于 7%。在发布当分钟,这一比例跃升至 15%,随后持续攀升,最后三分钟达到 47–65%。图中的累计曲线仅达到 22.6%,因为它将发布后的工单与发布前的所有流量一起计算平均值。因此,告警应依据每分钟占比,而非累计占比。
以发布时间为界,完整的类别分布如下。
run_athena "
SELECT IF(ts < timestamp '${LAUNCH_TS}', '1-before launch', '2-after launch') AS period,
predicted_category, count(*) AS n
FROM preds GROUP BY 1, 2 ORDER BY 1, 3 DESC"
period predicted_category n
1-before launch ProductFridge 91
1-before launch ProductWasher 83
1-before launch ProductDishwasher 74
1-before launch ProductOven 74
1-before launch ProductMicrowave 59
1-before launch Other 19
2-after launch Other 184
2-after launch ProductFridge 84
2-after launch ProductOven 66
2-after launch ProductDishwasher 64
2-after launch ProductWasher 58
2-after launch ProductMicrowave 44Other 从发布前占工单的 4.8%(400 张中的 19 张),升至发布后的 36.8%(500 张中的 184 张),成为最大的类别。
第 9 步,Other 类别中包含什么?
run_athena "
SELECT word, count(*) AS freq
FROM preds CROSS JOIN UNNEST(regexp_extract_all(lower(ticket_text), '[a-z0-9-]{4,}')) AS t(word)
WHERE predicted_category = 'Other'
AND word NOT IN ('this','that','with','from','have','since','week','help','need','again','time',
'month','second','take','look','someone','order','last','after','when','onto')
GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT 10"
word freq
arctis 141
unit 40
mini 33
cooling 30
link 30
lost 30
loudly 30
rattles 30
wi-fi 30
blows 28Other 类别并非由互不相关的工单混杂而成。它主要涉及同一个产品名称 arctis,以及制冷电器相关词汇,这表明出现了一个路由器尚无对应标签的新类别。
第 10 步,规模有多大,模型的置信度能否提示这一问题?
在整个流量中搜索新产品,而不仅仅搜索 Other 类别。
run_athena "
SELECT IF(ts < timestamp '${LAUNCH_TS}', '1-before launch', '2-after launch') AS period,
predicted_category, count(*) AS n
FROM preds WHERE regexp_like(lower(ticket_text), 'arctis|air condition')
GROUP BY 1, 2 ORDER BY 1, 3 DESC"
period predicted_category n
2-after launch Other 164
2-after launch ProductFridge 14共有 178 张空调工单,占全部流量的 19.8%。这些工单在发布前均未出现。它们分为两组。
- 164 张被分到
Other。在六标签模式下,这是正确答案,因为Other正是为这种情况设置的。路由器没有出故障。分类体系缺少一个类别,因此这些工单进入了通用队列,而未交给负责该产品的团队。 - 14 张被分到
ProductFridge。这些是真正的错误路由,冰箱团队现在收到了空调工单。
接下来,检查模型对这些已知错误路由的置信度。
run_athena "
SELECT predicted_category, confidence, count(*) AS n FROM preds
WHERE regexp_like(lower(ticket_text), 'arctis|air condition')
GROUP BY 1, 2 ORDER BY 1, 2 DESC"
predicted_category confidence n
Other 1.0 157
Other 0.9 7
ProductFridge 0.95 1
ProductFridge 0.9 9
ProductFridge 0.8 2
ProductFridge 0.7 1
ProductFridge 0.0 1在 14 张被错误路由的工单中,有 10 张报告的置信度为 0.9 或更高。诸如“保留满足 confidence >= 0.9 的预测”这样的标注规则,会保留 71% 的已知错误标签。这是因为 confidence 是我们要求模型填写的字段,并非经过校准的概率。如果需要真实的不确定性信号,请向 vLLM 请求 token 的 logprobs,并读取类别 token 对应的概率,而非使用模型自报的数值。需要为额外的载荷大小预留预算,因为每次响应都会捕获 logprobs。
从诊断到已标注训练数据
数据科学家无需手动标注数百张工单,而是将 Athena 的发现编写为一项标注策略,即一个为每条捕获记录分配修正后标签的 SQL 视图。我们将被错误路由的空调工单重新标注为新类别。
第 11 步,标注策略
run_athena "
CREATE OR REPLACE VIEW labeled_training_data AS
WITH t AS (SELECT ticket_text, predicted_category, lower(ticket_text) AS txt FROM preds)
SELECT ticket_text, predicted_category,
CASE
-- 1. The new class, identified by keyword evidence, not by what the model predicted
WHEN regexp_like(txt, '\\barctis\\b|air condition|\\bac unit\\b|mini split')
AND NOT regexp_like(txt, 'fridge|refrigerat|freezer|washer|\\boven\\b|\\brange\\b|dishwasher|microwave')
THEN 'ProductAC'
-- 2. Keep the production decision when nothing hints at the new product
WHEN NOT regexp_like(txt, '\\barctis\\b|air condition|\\bac\\b|mini split')
THEN predicted_category
-- 3. Mixed signals: send to human review (Amazon SageMaker Ground Truth)
ELSE NULL
END AS corrected_category
FROM t"双反斜杠(\\b)是双引号字符串中的 shell 转义。Athena 接收到的是 \b,即正则表达式中的单词边界。
检查策略生成的结果。
run_athena "
SELECT coalesce(corrected_category, '(human review)') AS label, count(*) AS n,
count(DISTINCT ticket_text) AS distinct_texts,
count_if(corrected_category <> predicted_category) AS relabeled
FROM labeled_training_data GROUP BY 1 ORDER BY 2 DESC"
label n distinct_texts relabeled
ProductAC 178 114 178
ProductFridge 161 110 0
ProductWasher 141 96 0
ProductOven 140 97 0
ProductDishwasher 138 95 0
ProductMicrowave 103 82 0
Other 39 8 0这种启发式方法之所以有效,是因为新类别界限清晰,可以通过关键词识别。对于含义模糊的工单或相互重叠的类别,值为 NULL 的行会被送往 Ground Truth 进行人工标注。
第 12 步,构建训练文件
导出已标注的视图,并将其转换为聊天格式的 JSONL。允许的类别集合现在包含 ProductAC,与重新部署后客户端将发送的七标签提示词一致。将以下内容保存为 build_training_file.py。
cat > build_training_file.py <<'PY'
import csv, json, sys
CATS = ["ProductFridge", "ProductWasher", "ProductOven", "ProductDishwasher", "ProductMicrowave", "ProductAC", "Other"]
PROMPT = ("You are a support-ticket router for a home-appliance retailer. Route each ticket to the product it "
'concerns. Respond with ONLY a JSON object {"category": "...", "confidence": <0-1>} where category is '
"one of: " + ", ".join(CATS) + '. Use "Other" if the ticket does not clearly concern one of these products.')
n = 0
with open(sys.argv[1], newline="") as fin, open(sys.argv[2], "w") as fout:
for row in csv.DictReader(fin):
fout.write(json.dumps({"messages": [
{"role": "system", "content": PROMPT},
{"role": "user", "content": row["ticket_text"]},
{"role": "assistant", "content": json.dumps({"category": row["corrected_category"], "confidence": 1.0})},
]}) + "\n"); n += 1
print(f"wrote {n} training examples -> {sys.argv[2]}")
PY
run_athena "SELECT ticket_text, corrected_category FROM labeled_training_data
WHERE corrected_category IS NOT NULL" > /dev/null
aws s3 cp "${ATHENA_OUTPUT}${LAST_QID}.csv" labeled.csv --only-show-errors # Athena's own CSV: header + proper quoting
python3 build_training_file.py labeled.csv train.jsonl
aws s3 cp train.jsonl "s3://${BUCKET}/training/train.jsonl"
wrote 900 training examples -> train.jsonl使用 HyperPod 训练操作器对捕获数据进行微调
我们在提供模型服务的同一个集群上,使用 HyperPod 训练操作器在第二块 GPU 上进行微调。第一个端点始终持续提供服务。
第 13 步,训练脚本
脚本从 S3 下载基础模型和训练数据,并训练一个低秩自适应(LoRA)适配器。损失仅针对助手轮次计算,因此模型会学习输出标签,而不是重复提示词。随后,脚本将适配器合并回基础权重,使 vLLM 无需修改即可提供合并后模型的服务,并将合并后的模型上传到 S3。该作业通过 ConfigMap 将脚本挂载到训练 Pod 中。
cat > train.py <<'PY'
import os, boto3, torch
from datasets import load_dataset
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
s3 = boto3.client("s3")
def split(uri): b, _, k = uri[5:].partition("/"); return b, k
# 1. Stage base model + training data from S3
bucket, prefix = split(os.environ["BASE_MODEL_S3"])
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
for o in page.get("Contents", []):
dst = os.path.join("/work/base", os.path.relpath(o["Key"], prefix))
os.makedirs(os.path.dirname(dst), exist_ok=True); s3.download_file(bucket, o["Key"], dst)
s3.download_file(*split(os.environ["TRAIN_FILE_S3"]), "/work/train.jsonl")
print("[stage] base model and training data downloaded", flush=True)
# 2. LoRA SFT, loss only on the assistant turn (the label), not the prompt
tok = AutoTokenizer.from_pretrained("/work/base")
def encode(ex):
full = tok.apply_chat_template(ex["messages"], tokenize=False)
prompt = tok.apply_chat_template(ex["messages"][:-1], tokenize=False, add_generation_prompt=True)
ids = tok(full, add_special_tokens=False)["input_ids"]
n = len(tok(prompt, add_special_tokens=False)["input_ids"])
return {"input_ids": ids, "labels": [-100] * n + ids[n:]}
ds = load_dataset("json", data_files="/work/train.jsonl", split="train")
print(f"[data] {len(ds)} examples", flush=True)
ds = ds.map(encode, remove_columns=ds.column_names)
def collate(batch):
m = max(len(b["input_ids"]) for b in batch)
pad = lambda xs, v: [x + [v] * (m - len(x)) for x in xs]
return {"input_ids": torch.tensor(pad([b["input_ids"] for b in batch], tok.pad_token_id)),
"labels": torch.tensor(pad([b["labels"] for b in batch], -100)),
"attention_mask": torch.tensor(pad([[1] * len(b["input_ids"]) for b in batch], 0))}
model = AutoModelForCausalLM.from_pretrained("/work/base", torch_dtype=torch.bfloat16, device_map="cuda:0")
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]))
model.print_trainable_parameters()
Trainer(model=model, train_dataset=ds, data_collator=collate, args=TrainingArguments(
output_dir="/tmp/ckpt", num_train_epochs=float(os.getenv("EPOCHS", "2")), learning_rate=1e-4,
per_device_train_batch_size=8, bf16=True, logging_steps=10, save_strategy="no", report_to=[],
warmup_ratio=0.1, lr_scheduler_type="cosine")).train()
# 3. Merge the adapter into the base weights (a plain model vLLM can serve) and upload it
model.merge_and_unload().save_pretrained("/work/out", safe_serialization=True)
tok.save_pretrained("/work/out")
bucket, prefix = split(os.environ["OUTPUT_S3"])
for f in os.listdir("/work/out"):
s3.upload_file(os.path.join("/work/out", f), bucket, f"{prefix.rstrip('/')}/{f}")
print(f"[done] merged model uploaded to {os.environ['OUTPUT_S3']}", flush=True)
PY
kubectl create configmap router-train --from-file=train.py第 14 步,提交 HyperPodPyTorchJob
cat > finetune-job.yaml <<'YAML'
apiVersion: sagemaker.amazonaws.com/v1
kind: HyperPodPyTorchJob
metadata:
name: router-ft
namespace: default
spec:
nprocPerNode: "1"
runPolicy:
jobMaxRetryCount: 2
cleanPodPolicy: All # release the GPU as soon as the job finishes
logMonitoringConfiguration: # restart a job that never starts, or goes quiet mid-run
- name: JobStart
logPattern: '.*loss.*'
expectedStartCutOffInSeconds: 1200
- name: JobHangingDetection
logPattern: '.*loss.*'
expectedRecurringFrequencyInSeconds: 600
replicaSpecs:
- name: pod
replicas: 1
template:
metadata:
labels: { app: router-ft }
spec:
serviceAccountName: ${TRAIN_SA} # EKS Pod Identity -> S3 read/write
nodeSelector:
node.kubernetes.io/instance-type: ${TRAIN_INSTANCE_TYPE}
restartPolicy: Always # required by the operator; retries live in runPolicy
containers:
- name: pytorch
image: vllm/vllm-openai:v0.10.0 # already has torch + transformers + boto3
command: ["bash", "-c"]
args:
- pip install -q peft==0.14.0 datasets==3.2.0 hyperpod-elastic-agent==1.1.3 &&
hyperpodrun --nnodes=1 --nproc_per_node=1 /scripts/train.py
env:
- { name: BASE_MODEL_S3, value: "s3://${BUCKET}/${MODEL_LOCATION}/" }
- { name: TRAIN_FILE_S3, value: "s3://${BUCKET}/training/train.jsonl" }
- { name: OUTPUT_S3, value: "s3://${BUCKET}/${MODEL_V2_LOCATION}/" }
resources:
requests: { cpu: "2", memory: 24Gi, nvidia.com/gpu: 1 }
limits: { nvidia.com/gpu: 1 }
volumeMounts:
- { name: scripts, mountPath: /scripts }
- { name: work, mountPath: /work }
- { name: shm, mountPath: /dev/shm }
volumes:
- { name: scripts, configMap: { name: router-train } }
- { name: work, emptyDir: {} }
- { name: shm, emptyDir: { medium: Memory, sizeLimit: 8Gi } }
YAML
render < finetune-job.yaml | kubectl apply -f -
kubectl logs -l app=router-ft -flogMonitoringConfiguration是训练操作器的特色功能。如果启动后 20 分钟内没有出现loss行,或者运行期间进程仍存活但日志连续 10 分钟没有输出,操作器就会重启作业,以免任其消耗 GPU 时长。- 作业启动时会安装三个 Python 包。训练节点需要具备出站互联网访问能力,例如通过 NAT 网关访问,从 Docker Hub 拉取
vllm/vllm-openai镜像也同样需要。在没有互联网出口的集群中,应将这些包预装到 Amazon Elastic Container Registry(Amazon ECR)中的自定义镜像内,并移除pip install。
作业日志节选如下。
{'loss': 0.2484, 'grad_norm': 3.387, 'learning_rate': 3.91e-05, 'epoch': 0.09}
{'loss': 0.018, 'grad_norm': 0.0037, 'learning_rate': 8.26e-05, 'epoch': 0.18}
...
{'loss': 0.0, 'grad_norm': 0.000105, 'learning_rate': 2.93e-07, 'epoch': 1.95}
{'train_runtime': 59.68, 'train_samples_per_second': 30.16, 'train_loss': 0.0123, 'epoch': 2.0}
[done] merged model uploaded to s3://amzn-s3-demo-bucket/models/qwen2.5-3b-router-v2/
[HyperPodElasticAgent] ... Transitioned from AgentState.RUNNING to AgentState.COMPLETED
kubectl get hyperpodpytorchjob router-ft -o jsonpath='{range .status.conditions[*]}= {end}'
Created=True Completed=True在一块 L40S 上,训练耗时 60 秒。秩为 16 的 LoRA 训练约 2,990 万个参数,不到这个 31 亿参数模型的 1%。平均训练损失为 0.0123,逐步损失在第一个训练轮次内就降到了 0.0,这表明模型很容易记住 900 个模板化示例。使用真实数据时,应留出验证集并采用早停。这里我们依靠留出的评估集。
第 15 步,并行部署微调后的模型,同时保持捕获开启
无需编辑正在运行的端点,而是使用同一份清单文件,将新模型作为第二个端点部署到训练作业刚刚释放的 GPU 上。第一个端点会继续提供服务,直到你将客户端切换过去,因此重新部署不会造成停机,回滚也只需将客户端重新指向第一个端点。
export ENDPOINT_NAME="appliance-router-v2" MODEL_LOCATION="$MODEL_V2_LOCATION" SERVE_INSTANCE_TYPE="$TRAIN_INSTANCE_TYPE"
render < endpoint.yaml | kubectl apply -f -
kubectl get pods -l app=$ENDPOINT_NAME -o custom-columns='NAME:.metadata.name,READY:.status.containerStatuses[*].ready,NODE:.spec.nodeName'
NAME READY NODE
appliance-router-v2-c96594c5-fhs2x true,true,true,true hyperpod-i-0e0b756209b5e497a新端点会将捕获数据写入其自身的 uniqueID 下。由于 ENDPOINT_NAME 现在为 appliance-router-v2,重新执行第 6 步中的 CAPTURE_LOCATION 查找即可找到该前缀,因此你可以让第二个 Athena 表指向它,开展下一轮分析。切换客户端时,应在同一次发布中更新端点、标签集和引导式 JSON 枚举。
衡量提升效果
我们使用相同的 280 张留出工单测试了微调后的端点。
overall 280/280 = 100.00%
ProductFridge 40/40
ProductWasher 40/40
ProductOven 40/40
ProductDishwasher 40/40
ProductMicrowave 40/40
ProductAC 40/40
Other 40/40| 指标 | 微调前(最初上线时) | 微调后 |
| 留出集准确率(280) | 235 (83.9%) | 280 (100%) |
ProductAC(40) |
0/40,全部被路由到 Other |
40/40 |
Other(40) |
35/40 | 40/40 |
| 五个已有产品类别(200) | 200/200 | 200/200 |
| 手写探测工单(24 张,下文说明) | 16/24 | 20/24 |
微调让路由器学会了新类别,并且没有导致五个已有类别的表现退化。它还修复了五个在发布前就已存在的 Other 分类错误,最初上线的路由器将这些工单分到了 ProductFridge。
由于评估集和训练数据来自同一个生成器,我们还手写了 24 张探测工单,采用生成器从未产生过的表达风格。微调后模型的得分为 20/24。
MISS ProductFridge -> ProductAC: The cooling fan in my fridge is squealing.
MISS Other -> ProductAC: When will the Arctis 12K be back in stock?
MISS Other -> ProductAC: Can I get a quote to install central air in my house?
MISS Other -> ProductAC: Do you price match the Arctis at other stores?
overall 20/24 = 83.33%它正确路由了全部八张空调探测工单,但也学到了两条捷径,“制冷”意味着空调,而只要提到 Arctis 就意味着 ProductAC,包括库存和价格匹配问题。这两点都源于训练数据,标注策略将每张 Arctis 工单都分到了 ProductAC,而捕获流量中没有售前问题。新端点开启捕获后,下一轮捕获恰好就能收集到这些工单。
捕获会增加多少延迟?
我们直接进行了测量,将同样的 400 个路由请求从 Pod 内部分别发送到端口 8000(不捕获)或端口 8081(经过捕获代理)。我们以 8 个并发请求运行了三轮,另外还运行了一轮串行请求。
| 路径 | 并发数 | p50 | p99 | 吞吐量 |
| 直接访问 vLLM(8000),不捕获 | 8 | 200.7 毫秒 | 249.4 毫秒 | 39.1 次请求/秒 |
| 经过捕获代理(8081) | 8 | 200.0 毫秒 | 249.8 毫秒 | 39.1 次请求/秒 |
| 直接访问 vLLM(8000),不捕获 | 1 | 164.4 毫秒 | 206.9 毫秒 | 6.0 次请求/秒 |
| 经过捕获代理(8081) | 1 | 164.4 毫秒 | 207.0 毫秒 | 6.0 次请求/秒 |
并发数为 8 的各行是三轮测试的平均值。轮次之间的波动(p50 为 ±1 毫秒)大于两条路径之间的差异。
捕获数据的其他用途
推理数据写入 S3 后,同一批记录可以用于多种工作流。
- 改进模型。使用监督微调(本文已演示),将大模型的输出蒸馏到小模型中,或构建偏好对用于直接偏好优化(DPO)。
- 理解模型。运行 Athena 分析(本文已演示),利用真实提示词构建黄金回归测试集,设置漂移告警,发现新出现的意图,并检测格式错误的输出和拒绝回答。
- 运维与治理。将含义模糊的样本发送到 Ground Truth 进行标注,保留审计轨迹(建议使用第 1 层),回放引发某次事件的确切输入,并分析流量和载荷以进行成本归因。
成本考量
| 层级 | 大致成本影响 |
| 第 1 层(SageMaker 端点) | 由 SageMaker 在端点处捕获。你需要为载荷支付 S3 存储和请求费用 |
| 第 2 层(ALB 访问日志) | 仅需支付日志文件的 S3 存储费用 |
| 第 3 层(模型 Pod) | 三个边车容器在每个 Pod 中合计请求 250m CPU + 640 MiB 资源(NGINX 代理 100m/128Mi、OTel 收集器 100m/256Mi、s3-uploader 50m/256Mi),另需支付载荷的 S3 存储和请求费用 |
两项成本会随使用量增长。
- S3。我们的记录平均每条约 2.3 KB(3,955 条记录共 9.0 MB)。提示词和响应越长,成本也会按比例增加。上传器会在每个刷新间隔为每个 Pod 写入一个对象,间隔为 60 秒时,每个 Pod 每天约产生 1,440 次 PUT 请求。
- Athena 按扫描的数据量收费,因此应始终按分区列筛选。对于重复分析,可通过
CREATE TABLE AS SELECT(CTAS)查询将原始 JSON 转换为 Parquet。
当前价格请参阅 Amazon S3 定价和 Amazon Athena 定价。
清理
为避免产生不必要的费用,请清理本演示创建的资源。
kubectl delete inferenceendpointconfig appliance-router appliance-router-v2
kubectl delete hyperpodpytorchjob router-ft
kubectl delete configmap router-train
run_athena "DROP VIEW IF EXISTS labeled_training_data"; run_athena "DROP VIEW IF EXISTS preds"
run_athena "DROP TABLE IF EXISTS inference_captures"; run_athena "DROP DATABASE IF EXISTS ${ATHENA_DB}"
aws s3 rm "s3://${BUCKET}/capture/" --recursive
aws s3 rm "s3://${BUCKET}/athena-results/" --recursive
aws s3 rm "s3://${BUCKET}/training/" --recursive
aws s3 rm "s3://${BUCKET}/${MODEL_V2_LOCATION}/" --recursive结论
本文展示了如何使用 SageMaker HyperPod Data Capture 记录实时推理数据,并将其转化为训练数据。借助三个相互独立层级的捕获功能,你可以完成以下操作。
- 收集真实场景的训练数据,对服务延迟没有可测量的影响。
- 使用 Amazon Athena 大规模查询推理模式,无需管理基础设施。
- 将 Athena 诊断结果转化为可复现的 SQL 标注策略。
- 利用捕获的生产数据进行微调,并衡量前后明确的提升。
- 与 HyperPod 训练操作器和 SageMaker Ground Truth 集成,完成闭环中的其余环节。
我们在一个家电支持工单路由器上运行了完整的一轮闭环。捕获流量揭示了新产品的识别盲区,SQL 标注策略将这些捕获数据转化为训练数据。使用 HyperPod 训练操作器进行的 60 秒 LoRA 微调,运行在提供模型服务的同一个集群上。它将新类别的召回率从 0% 提升到 100%,并且没有导致任何已有类别的表现退化。这些训练数据在模型部署之前均不存在。
Data Capture 现已可用于安装了推理操作器的 SageMaker HyperPod 集群。要开始使用,请在 InferenceEndpointConfig 或 JumpStartModel 资源中添加 dataCapture 部分并部署。要在同一集群上完成闭环,请添加 amazon-sagemaker-hyperpod-training-operator EKS 附加组件。本演示的完整代码位于配套 GitHub 仓库。
更多信息请参阅 SageMaker HyperPod 推理文档和 HyperPod 训练操作器文档。
关于作者
来源:AWS Machine Learning Blog · aws.amazon.com

