aws/amazon-sagemaker-examples · 上手攻略
- 仓库:aws/amazon-sagemaker-examples
- 链接:https://github.com/aws/amazon-sagemaker-examples
- 分类:ai(机器学习 / MLOps 示例集)
- 作者:spark
- 更新:2026-07-15
是什么
官方维护的 Amazon SageMaker 示例笔记本仓库,由 AWS SageMaker 团队直接管理。它不是 SDK 本身,而是 SageMaker 各功能(数据准备、训练、推理、监控、Feature Store、SageMaker-Core、Studio 等)的 可运行 Jupyter Notebook 示范集合,覆盖从 XGBoost 入门到大规模分布式训练、LLM 微调、CV/NLP 任务、MLOps 流水线在内的几十类端到端场景。仓库定位是「教你怎么把 SageMaker 各组件拼成完整的生产链路」,不是某个单独库的代码。
社区贡献另有 aws/amazon-sagemaker-examples-community;官方仓只接收「尚未覆盖的新功能」示例,重复示例会被打回社区仓。
解决什么问题
- 不知道怎么用 SageMaker:文档零散,新手不知道从哪个 API 入手;本仓库按场景组织的 notebook 是「官方最佳实践蓝图」。
- SageMaker 组件太多:Training Jobs、Processing Jobs、Pipeline、Endpoint、Feature Store、Clarify、Model Monitor、Studio、JumpStart、SageMaker-Core 各自一套,notebook 把它们串起来。
- 复制可用脚手架:自带 S3、IAM Role、Notebook Instance 一键起环境,能直接改改跑生产。
- 新功能参考实现:SageMaker-Core 这种新 SDK 的范例会第一时间推到这个仓。
快速安装
提示:仓库本身就是 notebook 集合,没有「装」的概念;「安装」是指搭好运行环境。
方式 A:SageMaker Notebook Instance(最省事)
- AWS 控制台 → SageMaker → Notebook instances → Create。
- 选实例(如
ml.t3.medium),IAM Role 给 SageMakerFullAccess + S3 读写权限。 - 创建后点 Open Jupyter / JupyterLab。
- Jupyter 左侧 SageMaker Examples 标签 → 即可看到本仓 notebook 列表,一键加载到实例。
前置条件:
- AWS 账号
- 配好的 IAM User / Role(具备 SageMaker、S3、ECR 相关权限)
- 一个 S3 bucket 存训练数据 / 模型产物
方式 B:本地或 EC2 上跑
git clone https://github.com/aws/amazon-sagemaker-examples.git
cd amazon-sagemaker-examples
# 推荐用 conda / mamba 隔离
conda create -n smx python=3.11 -y
conda activate smx
# 装 SageMaker Python SDK V3(2026 年主线版本)
pip install -U "sagemaker-python-sdk>=3.0"
pip install -U boto3 sagemaker-core jupyterlab
V3 支持 Python 3.10 / 3.11 / 3.12(截至 2026-05 的官方文档)。
sagemaker-core是新的面向对象 SDK,用来替代部分 Boto3 直调场景,本仓有sagemaker-core/子目录专门放它的范例。
把 IAM Role ARN 和 S3 bucket 写到环境变量:
export SAGEMAKER_ROLE_ARN=arn:aws:iam::123456789012:role/SageMakerExecutionRole
export SAGEMAKER_BUCKET=my-sagemaker-bucket
export AWS_REGION=us-east-1
然后 jupyter lab 启动,按目录挑 notebook 即可。
核心用法(可直接复制)
仓库按一级目录切场景,挑几个最常用的列一下:
1. XGBoost 训练 + Endpoint 部署
目录 training/sagemaker_xgboost/。最小骨架:
import sagemaker
import boto3
from sagemaker.inputs import TrainingInput
from sagemaker.xgboost import XGBoost
session = sagemaker.Session()
role = sagemaker.get_execution_role()
xgb = XGBoost(
entry_point="train.py", # 你的训练脚本
framework_version="2.0-1", # 容器里预装的 XGBoost 版本(核对 README)
instance_type="ml.m5.xlarge",
role=role,
sagemaker_session=session,
)
xgb.fit({"train": TrainingInput(s3_train_data, content_type="csv")})
predictor = xgb.deploy(
initial_instance_count=1,
instance_type="ml.m5.large",
)
print(predictor.predict([[0.5, 0.3, 0.1]]))
2. SageMaker Pipeline(Kubeflow 风格的 DAG)
目录 pipelines/。Pipeline 把预处理 → 训练 → 评估 → 注册 → 部署串成 DAG:
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.steps import TrainingStep, ProcessingStep
train_step = TrainingStep(name="Train", estimator=estimator, inputs={"train": train_input})
eval_step = ProcessingStep(name="Eval", processor=processor, inputs=[...])
pipeline = Pipeline(
name="MyMLPipeline",
steps=[train_step, eval_step],
sagemaker_session=session,
)
pipeline.upsert(role_arn=role)
pipeline.start()
3. Feature Store(V3 SDK)
from sagemaker.feature_store.feature_group import FeatureGroup
fg = FeatureGroup(name="user-clicks-v1", sagemaker_session=session)
fg.create(
record_identifier_name="user_id",
event_time_feature_name="event_time",
online_store_config={"EnableOnlineStore": True},
offline_store_config={"S3StorageConfig": {"S3Uri": f"s3://{bucket}/feature-store/"}},
)
fg.ingest(data_frame=df, wait=True)
V3 SDK 在 2026-05 加了 Lake Formation 列/行级访问控制 + Iceberg 表属性(compaction、snapshot 过期等),用 V3 接口即可一行开关。
4. SageMaker-Core(OOP 新 SDK)
目录 sagemaker-core/:
from sagemaker_core.main import create_training_job
tj = create_training_job(
training_job_name="demo-job",
algorithm_specification={
"training_image": "683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:2.0-1",
"training_input_mode": "File",
},
role_arn=role,
input_data_config=[...],
output_data_config={"s3_output_path": f"s3://{bucket}/output/"},
resource_config={"instance_type": "ml.m5.xlarge", "instance_count": 1},
stopping_condition={"max_runtime_in_seconds": 3600},
)
print(tj.arn) # 链式 API:资源对象直接传参,无需手填 ARN
TrainingJob / Model / Endpoint 都是带状态的对象,可读可等可链式组合。
5. JumpStart / Foundation Models / 异步推理
introduction_to_amazon_algorithms/→ SageMaker 内置算法sagemaker-fundemental-models/→ JumpStart 上一键拉 Llama、Claude、Mistral 等做微调/部署async-inference/→ 异步推理(长任务、大模型)studio/→ SageMaker Studio IDE 用法model-monitoring/→ Model Monitor 漂移检测
典型适用场景
- 第一次接触 SageMaker:照着
training/sagemaker_xgboost/一遍跑通,30 分钟上手。 - LLM 微调 / RAG:参考
sagemaker-jumpstart/、sagemaker-fundemental-models/,能直接在托管环境里拉 HuggingFace 模型训练。 - 数据 + 模型治理:Feature Store + Model Monitor + Clarify 一条龙,对应
feature_store/、model-monitoring/、clarify/。 - 批处理 ETL + 调度:Processing Job + Step Functions / Airflow 编排,参考
processing/。 - 生产级 MLOps:Pipeline + Model Registry + 部署审批链,参考
pipelines/。 - 新 SDK 升级迁移:SageMaker-Core 与 V3 Python SDK 范例先于文档,先看 notebook 比看 doc 更快。
坑与注意
- 跑 notebook 必产生 AWS 费用。Endpoint、Training Job、Notebook Instance 都按秒计费;不用了立刻
predictor.delete_endpoint()/ 关掉 instance,否则账单爆炸。 - 框架版本锁容器镜像。
framework_version="2.0-1"这种字符串决定 SageMaker 用哪个预装容器;升降级要查 SDK 的可用版本表(README /sagemaker.image_uris.retrieve()拿准确 URI),不要瞎猜。 - IAM Role 权限宁多勿少。Notebook 实例用
sagemaker.get_execution_role()拿到的是实例的 Role,不是你本地的。S3、ECR、日志组、CloudWatch、VPC 子网都得在信任策略里。 - SageMaker Python SDK V2 ↔ V3 兼容期。Feature Store 在 2026-05 才补齐 V3;旧代码可能还是 V2 接口,混用会报
ImportError。装包时显式pip install "sagemaker-python-sdk>=3.0"。 - 网络:训练 / 推理默认走公网拉取数据;私有 S3、VPC 内部署需要额外配
subnets+security_group_ids,Notebook 也要在 VPC 里。 - 数据上传位置:默认 SageMaker 把训练数据放在
s3://{bucket}/{prefix}/,输入TrainingInput(s3_train_data, content_type="csv")时路径必须真实存在。 - 仓内 notebook 可能落后于最新 SDK。AWS 团队维护有节奏,遇到
xxx has no attribute先升级sagemaker/boto3。 - 地区差异。SageMaker 不是所有 region 都开放全部实例类型和功能;新功能(如 SageMaker-Core、JumpStart 新模型)通常先在
us-east-1/us-west-2。
与同类对比
| 仓库 | 定位 | 与本仓区别 |
|---|---|---|
aws/amazon-sagemaker-examples-community |
社区示例补充 | 官方仓只收新功能示例,社区仓收通用 / 行业方案 |
aws/amazon-sagemaker-developer-guide |
概念文档 | 本仓是「跑得起来」的代码,文档只讲 API |
aws/deep-learning-containers |
训练/推理容器镜像 | 本仓用这些容器;仓里也讲怎么选镜像 |
HuggingFace transformers / sft 脚本 |
通用训练脚本 | 不托管、不带 Feature Store / Pipeline / Endpoint |
| Vertex AI Samples / Azure ML Samples | 其他云厂商 MLOps 示例 | 同类思路,但 API / IAM 模型完全不同;跨云迁移要重写 |
如果只用开源框架(HF / PyTorch Lightning)做训练,不需要这个仓;一旦用上 SageMaker 托管训练 + 部署 + MLOps,它就是最权威的代码范例集。
一句话推荐结论
SageMaker 用户的事实标准范例库:第一次上 SageMaker 必须先克隆一份照着改;新功能(SageMaker-Core、V3 Feature Store)官方会先在这里放参考实现,比文档更新快。代价是每个跑起来的 notebook 都会产生 AWS 账单,记得用完关 endpoint / 删 instance。