AWS 大数据深度剖析(第九篇):SageMaker 与机器学习平台——从训练到生产
全面解析 SageMaker AI:Studio 笔记本、Feature Store、训练作业、实时 Endpoint、Model Monitor,以及它们如何融入推荐系统的 MLOps 工作流。
数据已就绪,特征已计算,在线服务层已搭建完成——现在是时候训练和部署模型了。这正是 Amazon SageMaker 登场的地方。
本章将 SageMaker 作为一个伞形产品来讲解:SageMaker 并不是单一服务,而是一组覆盖整个机器学习生命周期的子服务集合。
什么是 SageMaker
一句话定义
Amazon SageMaker = AWS 面向全流程的全托管机器学习平台。机器学习所需的一切——数据探索、特征工程、训练、超参数调优、部署和监控——都可以在这一个 AWS 服务中完成。
命名变化(容易混淆——2024 re:Invent 之后到 2026 的结构)
| 名称 | 含义 | 状态(2026-05) |
|---|---|---|
| SageMaker AI | 原来的 SageMaker。本章讨论的所有机器学习/基础模型的训练和推理能力都归属于此 | GA |
| SageMaker Lakehouse | 统一访问 S3 + Redshift + 联邦数据源 | GA |
| SageMaker Unified Studio | 融合 AI + Lakehouse + Glue Studio + EMR Notebook + Bedrock IDE 的统一 IDE | 2025 GA |
| SageMaker Catalog | 基于 DataZone 的治理层(数据 + 模型 + 项目) | GA |
| Amazon SageMaker(新品牌) | 覆盖以上四大支柱的伞形品牌 | — |
当我们说”SageMaker”时,通常指的是 SageMaker AI(机器学习平台)。Lakehouse 部分已在第 2-4 篇中介绍过(S3 + Iceberg + Glue Catalog)。
2025-2026 新增内容:Unified Studio GA、IDE 内嵌 Q Developer、可直接从 SageMaker Studio 调用 Bedrock 基础模型、HyperPod 任务治理与弹性训练计划。
SageMaker 的 5 大核心能力
数据准备:Studio 与 Processing Job
SageMaker Studio 是一个基于浏览器、与 AWS 服务集成的 JupyterLab 环境。
- 编写 Python 笔记本,运行
wr.athena.read_sql_query(...)直接查询数据 - 集成 Spark / SKLearn 容器
- JupyterLab Spaces:每个用户拥有独立隔离的环境
Processing Job 用于运行数据预处理脚本:
- 启动 EC2,运行你的 Python 脚本,完成后自动销毁
- 适用于:特征生成、ETL、数据清洗
- 类似 EMR 但更轻量(无需 Spark 集群)
from sagemaker.sklearn.processing import SKLearnProcessor
processor = SKLearnProcessor(
role=role, instance_type='ml.m5.xlarge', instance_count=2,
)
processor.run(
code='preprocess.py',
inputs=[ProcessingInput(source='s3://.../sample/', destination='/opt/ml/processing/input/')],
outputs=[ProcessingOutput(source='/opt/ml/processing/output/', destination='s3://.../processed/')],
)
特征管理:SageMaker Feature Store
这在推荐场景中尤为重要。
问题所在:训练和推理必须保持特征一致性。
- 训练时你使用从
ads_user_features读取的特征 X - 服务时推理也需要同样的特征 X,但通过 DynamoDB 单点查询获取
- 两侧的字段名、编码方式和默认值必须完全一致——手动同步极易出错
Feature Store 的解决方案:
Define a Feature Group:
user_features:
- user_id (record id)
- event_time (event time)
- age, city, ctr_7d, last_5_clicks, ...
|
| ingest()
v
+-----------------------------+
| Offline Store (S3+Iceberg) | <-- Read during training, auto PIT queries
| Online Store (DynamoDB) | <-- Read at inference, millisecond latency
+-----------------------------+
^
| auto sync
关键特性:
- 离线存储(Offline Store):S3 + Iceberg,按 event_time 自动分区
- 在线存储(Online Store):内置 KV(类似 DynamoDB,由 AWS 全托管)
- 自动同步(Auto Sync):写入离线存储 -> 立即同步到在线存储
- PIT 查询:
get_features_at(event_time)自动获取该时间点的快照
Feature Store vs. 自建(DynamoDB + Iceberg):
| Feature Store | 自建 | |
|---|---|---|
| 在线/离线一致性 | 自动 | 自行维护同步作业 |
| PIT 查询 | 一次 API 调用 | 自行编写 Iceberg 时间旅行 SQL |
| 灵活性 | 中等(schema 受框架约束) | 高 |
| 成本 | 略贵 | 更便宜 |
建议:在 POC 阶段自建(DynamoDB + Iceberg);生产化时切换到 Feature Store。对于复杂场景,从第一天起就使用 Feature Store。
官方文档:https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store.html
训练:Training Jobs
内置算法
AWS 提供了 17 种以上的内置算法(XGBoost / LinearLearner / FactorizationMachine / KMeans / 常见深度学习模型):
from sagemaker.xgboost.estimator import XGBoost
xgb = XGBoost(
entry_point='train.py',
instance_type='ml.m5.2xlarge',
instance_count=1,
role=role,
framework_version='1.7-1',
)
xgb.fit({'train': 's3://.../train/', 'val': 's3://.../val/'})
自定义容器
PyTorch / TensorFlow / JAX 都有官方容器;对于自定义代码和依赖库:
from sagemaker.pytorch import PyTorch
estimator = PyTorch(
entry_point='train_two_tower.py',
framework_version='2.1.0',
instance_type='ml.g5.xlarge', # GPU
role=role,
hyperparameters={'lr': 0.001, 'embedding_dim': 64},
)
estimator.fit({'train': 's3://.../sample/'})
超参数调优
自动调优(贝叶斯优化 / 网格搜索 / 随机搜索):
from sagemaker.tuner import HyperparameterTuner, ContinuousParameter
tuner = HyperparameterTuner(
estimator=xgb,
objective_metric_name='validation:auc',
hyperparameter_ranges={'eta': ContinuousParameter(0.01, 0.5)},
max_jobs=20, max_parallel_jobs=4,
)
tuner.fit(...)
分布式训练
跨多机多 GPU 的数据并行 / 模型并行 / 流水线并行。
定价
按训练实例类型 + 时长计费,秒级计费。停止训练即刻停止计费。
- ml.m5.xlarge:约 $0.23/小时
- ml.g5.xlarge(GPU):约 $1.4/小时
- ml.p4d.24xlarge(8x A100):约 $32/小时
官方文档:https://docs.aws.amazon.com/sagemaker/latest/dg/train-model.html
部署:Endpoints
训练完成后,模型会保存到 S3,并部署到 Endpoint 上进行在线推理。
实时 Endpoint(Real-Time Endpoint)
启动 EC2 + 加载模型 + 暴露 HTTP API:
predictor = xgb.deploy(
initial_instance_count=2,
instance_type='ml.m5.xlarge',
endpoint_name='rank-model-v1',
)
# Invoke
result = predictor.predict({'features': [...]})
特点:
- P99 约 30-50ms(含网络)
- 7x24 在线,按实例小时计费
- 支持 Auto Scaling(随 QPS 增长自动扩容节点)
Serverless 推理
按调用计费,空闲时零成本:
from sagemaker.serverless import ServerlessInferenceConfig
predictor = model.deploy(
serverless_inference_config=ServerlessInferenceConfig(
memory_size_in_mb=4096, max_concurrency=20,
)
)
冷启动会带来数秒延迟——不适合推荐热路径(后者要求稳定的毫秒级延迟)。
多模型 Endpoint(MME)
单个 Endpoint 加载 N 个模型(按需惰性加载),适合长尾模型(每个模型单独 QPS 较低)。
异步 Endpoint / Batch Transform
批量推理(例如每天为全站所有用户打一次分)。
Endpoint 中的 A/B 测试
一个 Endpoint 可以承载多个 Production Variant,并按权重分流流量:
predictor.update_endpoint(
initial_instance_count=2, instance_type='ml.m5.xlarge',
new_endpoint_config_name='ab-test-config',
# variant A 90% + variant B 10%
)
这让模型的灰度(Canary)发布变得非常友好。
官方文档:https://docs.aws.amazon.com/sagemaker/latest/dg/deploy-model.html
监控:Model Monitor
模型上线后,最重要的不是速度,而是持续的质量。Model Monitor 会跟踪:
| 监控类型 | 检测内容 |
|---|---|
| 数据质量(Data Quality) | 输入特征分布是否发生漂移(概念漂移) |
| 模型质量(Model Quality) | 预测值与真实标签的 AUC / 误差 |
| 偏差漂移(Bias Drift) | 不同用户群体间预测结果的公平性 |
| 特征归因(Feature Attribution) | 特征重要性是否保持稳定 |
输出告警 -> CloudWatch -> Slack / 邮件。当检测到漂移时,可自动触发重新训练。
官方文档:https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor.html
客户场景:SageMaker 使用模式
双塔召回模型
# Training (SageMaker Training Job)
PyTorch(
entry_point='train_two_tower.py',
instance_type='ml.g5.xlarge',
role=role,
).fit({'train': 's3://.../ads_sample_follow/'})
# Output:
# user_tower.pt (user tower weights)
# item_tower.pt (item tower weights)
# Item embedding offline pre-computation (Processing Job)
SKLearnProcessor(...).run(
code='compute_item_embedding.py',
# Load item_tower.pt, compute vectors for all items on the platform
# Output: item_id, embedding[64]
outputs=[ProcessingOutput(destination='s3://.../item_embeddings/')]
)
# Write to OpenSearch k-NN (via Glue Job or Lambda)
# Deploy user_tower as an Endpoint
PyTorchModel(model_data='s3://.../user_tower.tar.gz').deploy(
instance_type='ml.m5.xlarge', initial_instance_count=2,
endpoint_name='user-tower-encoder',
)
# Recommendation service calls -> compute user vector in real-time -> query OpenSearch
LightGBM 排序模型
# Training
SKLearn(
entry_point='train_lgb.py',
instance_type='ml.m5.4xlarge',
).fit({'train': 's3://.../ads_sample_ctr/'})
# Deployment
predictor = SKLearnModel(...).deploy(
instance_type='ml.c5.xlarge', initial_instance_count=4,
endpoint_name='rank-lgb-v1',
)
# Recommendation service scores each candidate
scores = predictor.predict(features_for_50_candidates)
端到端编排
MWAA DAG:
04:00 SageMaker Training: train_recall_two_tower
04:00 SageMaker Training: train_rank_lgb
05:00 SageMaker Processing: compute_item_embeddings
05:30 Glue Job: write item_embeddings -> OpenSearch
06:00 Lambda: deploy new endpoints (Canary 10%)
10:00 Lambda: ramp up to 50%
14:00 Lambda: full traffic
GenAI 时代的 SageMaker 与 Bedrock(2026 现状)
尽管本客户场景是经典推荐系统而非 LLM,但到 2025-2026 年,AWS 的 GenAI 技术栈已相当成熟。以下是完整的全景图,供你日后需要 RAG / Agent / 内容生成时参考:
SageMaker AI 侧(自行训练与自行部署)
- JumpStart:开源模型市场(Llama 3 / Mistral / Stable Diffusion / DeepSeek 等),一键部署
- HyperPod:大模型训练集群(千卡 GPU 规模);2025 年新增任务治理 + 弹性训练计划(按时间段预留 GPU 容量)
- Inference Components:多个模型共享同一 GPU 实例,大幅降低长尾 LLM 的部署成本
- MLflow on SageMaker:托管版 MLflow,用于实验跟踪
Amazon Bedrock 侧(基于 API 的模型访问)
| 能力 | 说明 |
|---|---|
| 基础模型(Foundation Models) | Claude 4 系列 / Llama 3.x / Mistral / Cohere / Amazon Nova(Micro/Lite/Pro/Premier 文本 + Canvas 图像 + Reel 视频) |
| Bedrock Knowledge Bases | 托管 RAG,支持 S3 Vectors / OpenSearch / Aurora pgvector 后端,以及结构化数据检索 |
| Bedrock AgentCore + Agent Registry | 2025 年新推出,托管的 Agent 运行时 + 面向多智能体 / 工具调用的中央注册表 |
| Bedrock Guardrails | 内容安全 + PII 过滤 |
| Bedrock Prompt Management / Flows | Prompt 版本管理 + 可视化编排 |
Amazon Q
- Q Developer:内嵌于 IDE 的 AI 编程助手(已集成到 SageMaker Unified Studio)
- Q in QuickSight:BI 自然语言查询、Scenarios(What-if 分析)、自动生成 Topics
- Q Business:企业知识库问答
对于该客户的社交应用,如果日后需要”AI 评论生成 / 内容审核 / 智能客服”,可从 Bedrock 入手;如果需要私有 LLM 微调,则使用 SageMaker HyperPod。
Feature Store:用还是不用
这个决策在客户场景中常常引发争论。以下是一个决策框架:
| 情形 | 选择 |
|---|---|
| 团队 < 5 人,仅 1-2 个模型 | 不用——自建 DynamoDB + Iceberg 更轻量 |
| 模型 > 5 个,特征复用度高 | 用——避免重复定义特征 |
| 多团队协作 | 用——提供统一的注册表 |
| 对在线/离线一致性要求严格 | 用 |
| 对性能 / 成本极度敏感 | 不用——自建可做更精细的调优 |
对于 1-2 个模型的 POC 阶段,先自建以验证业务价值,之后再切换到 Feature Store。
本章小结
| 子服务 | 角色 |
|---|---|
| Studio / Notebook | 数据探索 + 模型实验 |
| Processing Job | 数据预处理(轻量级 ETL) |
| Feature Store | 在线/离线一致的特征平台 |
| Training Job | 托管模型训练(秒级计费) |
| Hyperparameter Tuning | 自动化超参数优化 |
| Endpoint | 在线推理(Real-time / Serverless / Async / MME) |
| Model Monitor | 数据 / 质量漂移监控 |
| JumpStart | 一键部署开源模型(面向 GenAI) |
SageMaker 的核心价值:让机器学习工程师专注于模型,而非基础设施。
下一章将把所有组件组装成最终架构,并给出成本估算。
参考资料
- Amazon SageMaker Developer Guide — AWS Documentation
- Amazon SageMaker Feature Store — AWS Documentation