在线AI教程 / AI部署

[Amazon Bedrock] 用 Amazon SageMaker HyperPod Data Capture 构建模型改进飞轮

· 转自:aws.amazon.com

人工智能 用 Amazon SageMaker HyperPod Data Capture 构建模型改进飞轮 部署在 Amazon SageMaker HyperPod 上的基础模

转载本文转自「aws.amazon.com」,版权归原作者所有,内容已摘录正文、去除外部链接。

人工智能

用 Amazon SageMaker HyperPod Data Capture 构建模型改进飞轮

部署在 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 endpoint第 2 层:负载均衡器第 3 层:模型 Pod 捕获内容完整的请求/响应 payloadApplication Load Balancer (ALB) 访问日志字段:请求行、状态码、耗时、客户端 IP、user agent完整的请求/响应 payload 以及事件元数据 管理方SageMaker 原生数据捕获ALB 访问日志HyperPod 推理算子(NGINX + OTel collector + S3 uploader sidecar) 最适用于合规、Model Monitor、审计低成本的流量与错误率监控调试、分析、训练数据采集 配置sagemakerEndpoint: — 采样 %、输入/输出、AWS KMSloadBalancer: { enabled: true }modelPod: — 采样 %、输入/输出、buffer、最大 payload 大小、AWS KMS、内容类型

第 1 层和第 3 层都存完整的 payload,两层同时开启会把每条记录存两遍。合规和 Model Monitor 用第 1 层,只需要流量元数据时用第 2 层,打算真正使用 payload 时用第 3 层。本文只用第 3 层。由于第 3 层记录的是完整 payload,其中可能包含姓名、地址和订单号,所以要在这些数据变成训练数据之前先做好保护:用采样、AWS Key Management Service (AWS KMS) 加密(kmsKeyId)、S3 生命周期规则,以及 personally identifiable information (PII) 脱敏(例如借助 Amazon Comprehend)。

先决条件

一个由 Amazon Elastic Kubernetes Service (Amazon EKS) 编排的 SageMaker HyperPod 集群,已安装推理算子(为模型部署设置 HyperPod 集群),并已安装训练算子的 EKS add-on amazon-sagemaker-hyperpod-training-operator(安装训练算子)。 两块可用的 NVIDIA GPU,一块用于提供服务,一块用于训练。我们用 ml.g6e.8xlarge 提供服务、ml.g6e.xlarge 做训练(各配一块 48 GB NVIDIA L40S)。提供服务的 Pod 在 endpoint 的整个生命周期里一直占着它的 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 加三个 sidecar。穿过 NGINX 代理的每个请求都会被复制到 OpenTelemetry collector,批量处理后经一个 Mountpoint-S3 卷写入 S3。Athena 就地读取这些文件。训练算子把微调作为 HyperPodPyTorchJob 跑在第二块 GPU 上,新模型由同样开启捕获的第二个 endpoint 提供服务。

第 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 driver 角色。 第 3 层捕获通过 Mountpoint-S3 卷写入,driver 以它自己的 IAM roles for service accounts (IRSA) 角色做认证,而不是用 Pod 的服务账户。它需要在捕获存储桶上有 s3:PutObject、s3:AbortMultipartUpload、s3:DeleteObject 权限;如果设置了 kmsKeyId,还要 kms:Decrypt、kms:GenerateDataKey、kms:DescribeKey。缺了这些,endpoint 依然健康、请求照样成功,但不会出现任何捕获。参见 Mountpoint for Amazon S3 CSI driver。 推理算子的执行角色。 它需要在捕获存储桶上有 s3:PutObject;如果设置了 kmsKeyId,还要 kms:Decrypt 和 kms:GenerateDataKey。捕获文件本身是通过 CSI driver 角色写入的,所以没有捕获出现时,先查这个角色。 训练 Pod 的服务账户($TRAIN_SA)。 通过 EKS Pod Identity 获得对基础模型和训练数据的读权限,以及对合并后模型的写权限。 Athena。 对捕获前缀的读权限,再加一个查询结果存放位置。

启用 Data Capture

接下来三步会部署开启第 3 层捕获的路由器,确认 Pod 跑起了捕获 sidecar,并核实记录确实到达了 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

在我们的这次运行里,kubectl apply 之后大约五分钟 Pod 才就绪,其中大部分时间花在下载权重上。

第 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 \ -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 按 endpoint 生成。每一行都是一次推理,采用下面这种 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 的 guided JSON decoding 把每张工单归到六个类别之一:ProductFridge、ProductWasher、ProductOven、ProductDishwasher、ProductMicrowave,或者兜底的 Other。guided decoding 意味着它只能返回带这些标签之一的有效对象:

{"category": "ProductWasher", "confidence": 1}

模型部署之后,这家零售商推出了自己的空调产品线——Arctis 系列(Arctis 9K、12K、Mini 等)。路由器没有对应它们的类别,它没法说「这是新东西」,只能在自己认识的最接近的标签里挑一个。除非把每个请求和响应都记下来,否则响应一返回,证据就消失了。

合成流量

我们生成了两个合成数据集:

生产流量: 900 张工单,用路由器原来的六标签 prompt,在 15 分钟内通过捕获代理按顺序重放。前 400 张在发布之前,完全没提空调;剩下 500 张里,Arctis 工单的占比从 15% 爬升到 55%。 评估集: 280 张带标签的工单,每类 40 张,包含新的 ProductAC。它是按内容独立留出的:用到的症状、句式模板和 Arctis 型号名在流量里从未出现。

每个生产请求长这样(system prompt 有删节):

{"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 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:///capture//pod/AllTraffic/

run_athena "": 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 前缀映射到分区,不需要 crawler,也不用 ADD PARTITION。data 字段声明成普通字符串,因为它们是 base64 文本。

run_athena " CREATE EXTERNAL TABLE IF NOT EXISTS inference_captures ( captureData struct< endpointInput: struct, endpointOutput: struct

,

eventMetadata struct, 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(...)) 把 payload 还原成 JSON;没有它,每次提取都会返回 NULL。工单就是用户消息(messages[1],因为 messages[0] 是 system prompt)。模型的答案是响应 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] 假定一条 system message 后面跟一条 user message。 捕获到的流量是客户端实际发来的东西,遇到多轮或 few-shot 请求,要相应调整提取方式。

第 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 44

Other 从发布前工单的 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 28

Other 这个桶并不是互不相干的工单混在一起。它由一个产品名 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 上的概率,而不是信模型的自报。要为此预留额外的 payload 体积,因为每条响应都会把 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 步:生成训练文件

把打好标签的视图导出,转成 chat 格式的 JSONL。允许的类别集合现在包含了 ProductAC,也就是重新部署后客户端会发送的那套七标签 prompt。把下面这段存成 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 训练算子在捕获数据上微调

我们在提供模型服务的同一个集群上微调,用第二块 GPU 上的 HyperPod 训练算子。第一个 endpoint 全程继续提供服务。

第 13 步:训练脚本

这个脚本从 S3 下载基础模型和训练数据,训练一个 low-rank adaptation (LoRA) 适配器。loss 只在 assistant 这一轮上计算,因此模型学的是产出标签,而不是复述 prompt。随后脚本把适配器合并回基础权重,让 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

logPattern: '.loss.' expectedStartCutOffInSeconds: 1200

logPattern: '.loss.' expectedRecurringFrequencyInSeconds: 600 replicaSpecs:

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:

image: vllm/vllm-openai:v0.10.0 # already has torch + transformers + boto3 command: ["bash", "-c"] args:

hyperpodrun --nnodes=1 --nproc_per_node=1 /scripts/train.py env:

resources: requests: { cpu: "2", memory: 24Gi, nvidia.com/gpu: 1 } limits: { nvidia.com/gpu: 1 } volumeMounts:

volumes:

YAML render < finetune-job.yaml | kubectl apply -f - kubectl logs -l app=router-ft -f

logMonitoringConfiguration 是训练算子最有辨识度的能力。 启动后 20 分钟内没有出现 loss 行,或者运行中进程还活着、日志却安静了 10 分钟,算子就会重启作业,而不是任它白白烧掉 GPU 机时。 作业启动时会装三个 Python 包。 训练节点需要出站互联网访问(例如经 NAT gateway),从 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 秒。rank 16 的 LoRA 训练约 2,990 万个参数,不到这个 31 亿参数模型的 1%。平均训练 loss 是 0.0123,每步 loss 在第一个 epoch 内就到了 0.0,说明模型很容易把 900 个模板化样本记住。换成真实数据,要留出验证集并早停。这里我们靠的是那份留出的评估集。

第 15 步:并排部署微调后的模型,捕获继续保持开启

不要去改正运行中的 endpoint,而是用同一份清单把新模型部署成第二个 endpoint,落到训练作业刚释放的那块 GPU 上。第一个 endpoint 会一直提供服务,直到你把客户端切过去,所以重新部署不会造成停机;要回滚,把客户端指回第一个 endpoint 就行。

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

新 endpoint 把捕获写到自己的 uniqueID 下。由于 ENDPOINT_NAME 现在是 appliance-router-v2,重跑第 6 步的 CAPTURE_LOCATION 查找就会找到那个前缀,于是可以把第二张 Athena 表指向它,做下一轮分析。迁移客户端时,要在同一次发布里一并更新 endpoint、标签集和 guided-JSON enum。

衡量提升

我们拿同样的 280 张留出工单去跑微调后的 endpoint:

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 — 全部路由到 Other40/40 Other (40)35/4040/40 五个既有产品类别 (200)200/200200/200 手写探针(24,稍后说明)16/2420/24

微调让路由器学会了这个新类别,五个既有类别也没有回退。它还修掉了上线前就存在、被当时那个路由器送进 ProductFridge 的 5 个 Other 错误。

由于评估集和训练数据出自同一个生成器,我们又手写了 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%

八张空调探针它全都路由对了,但也学到两条捷径:看到"cooling"就当空调,只要提到 Arctis 就给 ProductAC,连库存和比价问题也算。这两条都来自训练数据:标注策略把每张 Arctis 工单都送去了 ProductAC,而捕获到的流量里没有售前问题。新 endpoint 开着捕获,下一轮捕获收上来的恰恰就是这类工单。

捕获会增加多少延迟?

我们直接测了:同样 400 个路由请求,从 Pod 内部要么发到 8000 端口(不捕获),要么发到 8081 端口(经捕获代理)。8 并发跑了三轮,外加一轮串行:

路径并发p50p99吞吐量 直连 vLLM (8000),不捕获8200.7 ms249.4 ms39.1 req/s 经捕获代理 (8081)8200.0 ms249.8 ms39.1 req/s 直连 vLLM (8000),不捕获1164.4 ms206.9 ms6.0 req/s 经捕获代理 (8081)1164.4 ms207.0 ms6.0 req/s

并发为 8 的行是三轮的平均值。轮次之间的波动(p50 上 ±1 ms)比两条路径之间的差异还大。

捕获数据的其他用途

推理数据落到 S3 之后,同一批记录还能喂给许多工作流:

改进模型: 用监督微调(本文演示的),把大模型的输出蒸馏进小模型,或者构造偏好对做 direct preference optimization (DPO)。 理解模型: 跑 Athena 分析(本文演示的),用真实 prompt 构建黄金回归集,设置漂移告警,发现新冒出来的意图,检测格式错误的输出和拒答。 运维与治理: 把含糊的样本送到 Ground Truth 标注,保留审计轨迹(推荐用第 1 层),重放某次事故背后的原始输入,以及分析流量和 payload 做成本归因。

成本考量

层大致的成本影响 第 1 层 (SageMaker endpoint)由 SageMaker 在 endpoint 处捕获。你为 payload 支付 S3 存储和请求费用 第 2 层 (ALB 访问日志)只为日志文件付 S3 存储费 第 3 层 (模型 Pod)三个 sidecar 合计请求每个 Pod 250m CPU + 640 MiB(NGINX 代理 100m/128Mi、OTel collector 100m/256Mi、s3-uploader 50m/256Mi),外加 payload 的 S3 存储和请求费用

有两项成本随用量增长:

S3。 我们的记录平均每条约 2.3 KB(9.0 MB 里 3,955 条)。prompt 和响应越长,成本按比例往上走。uploader 每个 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% 拉到全部召回,任何既有类别都没有回退。而这些训练数据,在模型部署之前根本不存在。

Data Capture 现已在带推理算子的 SageMaker HyperPod 集群上可用。上手时,把 dataCapture 段加进 InferenceEndpointConfig 或 JumpStartModel 资源再部署即可。要在同一集群上把闭环合上,加上 amazon-sagemaker-hyperpod-training-operator 这个 EKS add-on。本演练的完整代码在随附的 GitHub 仓库里。

更多内容参见 SageMaker HyperPod 推理文档 和 HyperPod 训练算子文档。

关于作者

← 返回教程列表