构建端到端机器学习工作流与优化预测成本性能
1. Amazon SageMaker Pipelines 简介
Amazon SageMaker Pipelines 允许我们基于 SageMaker 的训练、调优、批量转换和处理脚本步骤,创建并运行端到端的机器学习工作流。与 Step Functions 相比,它具有以下特点:
- 可直接在 SageMaker Studio 中编写、运行、可视化和管理工作流,无需跳转至 AWS 控制台。
- 具备模型注册表,便于管理模型版本、仅部署已批准版本并跟踪模型谱系。
- 提供 MLOps 模板,这是通过 AWS 服务目录发布的 CloudFormation 模板集合,有助于自动化模型部署,还可添加自定义模板。
不过,SageMaker Pipelines 缺乏与其他 AWS 服务的集成,目前仅支持 SQS,而 Step Functions 支持更多计算和大数据服务。
2. 示例工作流步骤
以 Amazon Reviews 数据集和 BlazingText 算法为例,工作流包含以下步骤:
1. 处理步骤 :使用 SageMaker Processing 准备数据集。
2. 摄取步骤 :将处理后的数据集加载到 SageMaker Feature Store。
3. 数据集构建步骤 :使用 Amazon Athena 查询离线存储并将数据集保存到 S3。
4. 训练步骤 :在数据集上训练 BlazingText 模型。
5. 模型创建步骤 :将训练好的模型保存为 SageMaker 模型。
6. 模型注册步骤 :将模型添加到 SageMaker Pipelines 模型注册表。
在实际应用中,建议先使用 Jupyter Notebooks 进行实验和迭代,待项目成熟后再逐步自动化每个步骤,最终组装成工作流。可先使用单个 SageMaker Processing 作业自动化每个处理步骤,之后再结合 SageMaker Pipelines,且可使用相同的 Python 脚本,只需使用 Pipelines SDK 编写代码。
3. 定义工作流参数
可在工作流中定义参数,便于在其他项目中复用。参数可以是字符串、整数和浮点数,并可设置默认值。示例代码如下:
from sagemaker.workflow.parameters import ParameterInteger, ParameterString
# 创建 AWS 区域和实例类型参数
region = ParameterString(
name='Region',
default_value='eu-west-1')
processing_instance_type = ParameterString(
name='ProcessingInstanceType',
default_value='ml.m5.4xlarge')
processing_instance_count = ParameterInteger(
name='ProcessingInstanceCount',
default_value=1)
training_instance_type = ParameterString(
name='TrainingInstanceType',
default_value='ml.p3.2xlarge')
training_instance_count = ParameterInteger(
name='TrainingInstanceCount',
default_value=1)
# 创建输入数据、模型名称和模型审批状态参数
input_data = ParameterString(name='InputData')
model_name = ParameterString(name='ModelName')
model_approval_status = ParameterString(
name='ModelApprovalStatus',
default_value='PendingManualApproval')
4. 处理数据集
复用之前编写的处理脚本 preprocessing.py ,步骤如下:
1. 创建 SKLearnProcessor 对象:
from sagemaker.sklearn.processing import SKLearnProcessor
sklearn_processor = SKLearnProcessor(
framework_version='0.23-1',
role=role,
instance_type=processing_instance_type,
instance_count=processing_instance_count)
- 定义数据处理步骤:
from sagemaker.workflow.steps import ProcessingStep
from sagemaker.processing import ProcessingInput, ProcessingOutput
step_process = ProcessingStep(
name='process-customer-reviews',
processor=sklearn_processor,
inputs=[
ProcessingInput(source=input_data,
destination="/opt/ml/processing/input")],
outputs=[
ProcessingOutput(output_name='bt_data',
source='/opt/ml/processing/output/bt'),
ProcessingOutput(output_name='fs_data',
source='/opt/ml/processing/output/fs')],
code='preprocessing.py',
job_arguments=[
'--filename',
'amazon_reviews_us_Camera_v1_00.tsv.gz',
'--library',
'spacy']
)
5. 摄取数据集到 Feature Store
复用 ingesting.py 脚本,步骤如下:
1. 定义特征组名称:
import time
from time import gmtime, strftime
feature_group_name = 'amazon-reviews-feature-group-' + strftime('%d-%H-%M-%S', gmtime())
- 定义处理步骤:
step_ingest = ProcessingStep(
name='ingest-customer-reviews',
processor=sklearn_processor,
inputs=[
ProcessingInput(
source=step_process.properties.ProcessingOutputConfig.Outputs['fs_data'].S3Output.S3Uri,
destination="/opt/ml/processing/input")],
outputs = [
ProcessingOutput(
output_name='feature_group_name',
source='/opt/ml/processing/output/')],
code='ingesting.py',
job_arguments=[
'--region', region,
'--bucket', bucket,
'--role', role,
'--feature-group-name', feature_group_name,
'--max-workers', '32']
)
6. 构建数据集
复用 querying.py 脚本,设置输入为摄取步骤的输出,定义训练和验证数据集的输出:
step_build_dataset = ProcessingStep(
name='build-dataset',
processor=sklearn_processor,
inputs=[
ProcessingInput(
source=step_ingest.properties.ProcessingOutputConfig.Outputs['feature_group_name'].S3Output.S3Uri,
destination='/opt/ml/processing/input')],
outputs=[
ProcessingOutput(
output_name='training',
source='/opt/ml/processing/output/training'),
ProcessingOutput(
output_name='validation',
source='/opt/ml/processing/output/validation')],
code='querying.py',
job_arguments=[
'--region', region,
'--bucket', bucket,]
)
7. 训练模型
- 定义
Estimator模块:
from sagemaker.estimator import Estimator
from sagemaker import image_uris
container = image_uris.retrieve(
'blazingtext',
str(region))
prefix = 'blazing-text-amazon-reviews'
s3_output = 's3://{}/{}/output/'.format(bucket, prefix)
bt = Estimator(container,
role,
instance_count=training_instance_count,
instance_type=training_instance_type,
output_path=s3_output)
bt.set_hyperparameters(mode='supervised')
- 定义训练步骤:
from sagemaker.workflow.steps import TrainingStep
from sagemaker.inputs import TrainingInput
step_train = TrainingStep(
name='train-blazing-text',
estimator=bt,
inputs={
'train': TrainingInput(s3_data=step_build_dataset.properties.ProcessingOutputConfig.Outputs['training'].S3Output.S3Uri,
content_type='text/plain'),
'validation': TrainingInput(s3_data=step_build_dataset.properties.ProcessingOutputConfig.Outputs['validation'].S3Output.S3Uri,
content_type='text/plain')
}
)
8. 创建和注册模型
- 创建模型:
from sagemaker.model import Model
from sagemaker.workflow.steps import CreateModelStep
model = Model(
image_uri=container,
model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
sagemaker_session=session,
name=model_name,
role=role)
step_create_model = CreateModelStep(
name='create-model',
model=model,
inputs=None)
- 注册模型:
from sagemaker.workflow.step_collections import RegisterModel
step_register = RegisterModel(
name='register-model',
estimator=bt,
model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
content_types=['text/plain'],
response_types=['application/json'],
inference_instances=['ml.t2.medium'],
transform_instances=['ml.m5.xlarge'],
model_package_group_name='blazing-text-on-amazon-customer-reviews-package',
approval_status=model_approval_status
)
9. 创建管道
将所有步骤和参数组合,创建或更新管道:
from sagemaker.workflow.pipeline import Pipeline
pipeline_name = 'blazing-text-amazon-customer-reviews'
pipeline = Pipeline(
name=pipeline_name,
parameters=[region, processing_instance_type, processing_instance_count, training_instance_type, training_instance_count, model_approval_status, input_data, model_name],
steps=[step_process, step_ingest, step_build_dataset, step_train, step_create_model, step_register])
pipeline.upsert(role_arn=role)
10. 运行管道
- 启动管道执行:
input_data_uri = 'your_input_data_uri'
execution = pipeline.start(
parameters=dict(
InputData=input_data_uri,
ModelName='blazing-text-amazon-reviews')
)
- 在 SageMaker Studio 中查看管道执行情况。
- 查看每个步骤的谱系:
from sagemaker.lineage.visualizer import LineageTableVisualizer
viz = LineageTableVisualizer(session)
for execution_step in reversed(execution.list_steps()):
print(execution_step)
display(viz.show(
pipeline_execution_step=execution_step))
11. 部署模型
- 更改模型状态为已批准:在 SageMaker 资源 / 模型注册表中,右键单击模型,选择“更新模型版本状态”,将状态设置为“已批准”,并记录模型 ARN。
- 部署模型:
from sagemaker import ModelPackage
model_package_arn = 'arn:aws:sagemaker:eu-west-1:123456789012:model-package/blazing-text-on-amazon-customer-reviews-package/1'
model = sagemaker.ModelPackage(
role = role,
model_package_arn = model_package_arn)
model.deploy(
initial_instance_count = 1,
instance_type = 'ml.t2.medium',
endpoint_name='blazing-text-on-amazon-reviews')
- 测试模型:
from sagemaker.predictor import Predictor
bt_predictor = Predictor(
endpoint_name='blazing-text-on-amazon-reviews',
serializer=sagemaker.serializers.JSONSerializer(),
deserializer=sagemaker.deserializers.JSONDeserializer())
instances = [' I really love this camera , it takes amazing pictures . ']
payload = {'instances': instances,
'configuration': {'k': 3}}
response = bt_predictor.predict(payload)
print(response)
- 完成后删除端点。
12. 优化预测成本和性能
12.1 技术要求
- 需要 AWS 账户,可在 https://aws.amazon.com/getting-started/ 创建。
- 熟悉 AWS 免费套餐 https://aws.amazon.com/free/ 。
- 安装并配置 AWS 命令行界面 https://aws.amazon.com/cli/ 。
- 具备 Python 3.x 环境,建议安装 Anaconda 发行版 https://www.anaconda.com/ 。
- 安装 Git 客户端 https://git-scm.com/ 以访问代码示例 https://github.com/PacktPublishing/Learn-Amazon-SageMaker-second-edition 。
12.2 端点自动缩放
为在波士顿住房数据集上训练的 XGBoost 模型设置自动缩放,步骤如下:
1. 创建端点配置并构建端点:
import boto3
sm = boto3.client('sagemaker')
model_name = 'sagemaker-xgboost-2020-06-09-08-33-24-782'
endpoint_config_name = 'xgboost-one-model-epc'
endpoint_name = 'xgboost-one-model-ep'
production_variants = [{
'VariantName': 'variant-1',
'ModelName': model_name,
'InitialInstanceCount': 2,
'InitialVariantWeight': 1,
'InstanceType': 'ml.m5.large'}]
sm.create_endpoint_config(
EndpointConfigName=endpoint_config_name,
ProductionVariants=production_variants)
sm.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=endpoint_config_name)
- 定义可扩展目标:
app = boto3.client('application-autoscaling')
app.register_scalable_target(
ServiceNamespace='sagemaker',
ResourceId='endpoint/xgboost-one-model-ep/variant/variant-1',
ScalableDimension='sagemaker:variant:DesiredInstanceCount',
MinCapacity=2,
MaxCapacity=10)
- 应用缩放策略:
policy_name = 'xgboost-scaling-policy'
app.put_scaling_policy(
PolicyName=policy_name,
ServiceNamespace='sagemaker',
ResourceId='endpoint/xgboost-one-model-ep/variant/variant-1',
ScalableDimension='sagemaker:variant:DesiredInstanceCount',
PolicyType='TargetTrackingScaling',
TargetTrackingScalingPolicyConfiguration={
'TargetValue': 1000.0,
'PredefinedMetricSpecification': {
'PredefinedMetricType': 'SageMakerVariantInvocationsPerInstance'
},
'ScaleInCooldown': 60,
'ScaleOutCooldown': 60
}
)
- 发送流量到端点:
test_sample = '0.00632, 18.00, 2.310, 0, 0.5380, 6.5750, 65.20, 4.0900, 1, 296.0, 15.30, 396.90, 4.98'
smrt = boto3.Session().client(service_name='runtime.sagemaker')
while True:
smrt.invoke_endpoint(EndpointName=endpoint_name,
ContentType='text/csv',
Body=test_sample)
- 监控指标并根据负载调整实例数量。
- 完成后删除资源:
app.delete_scaling_policy(
PolicyName=policy_name,
ServiceNamespace='sagemaker',
ScalableDimension='sagemaker:variant:DesiredInstanceCount',
ResourceId='endpoint/xgboost-one-model-ep/variant/variant-1')
sm.delete_endpoint(EndpointName=endpoint_name)
sm.delete_endpoint_config(EndpointConfigName=endpoint_config_name)
总结
通过 Amazon SageMaker Pipelines,我们可以构建、运行和跟踪端到端的机器学习工作流,并且可以利用自动缩放等技术优化预测成本和性能。这些工具和技术有助于提高生产力,使高质量模型更快投入生产。
工作流步骤流程图
graph LR
A[处理步骤] --> B[摄取步骤]
B --> C[数据集构建步骤]
C --> D[训练步骤]
D --> E[模型创建步骤]
E --> F[模型注册步骤]
自动缩放步骤表格
| 步骤 | 操作 |
|---|---|
| 1 | 创建端点配置和端点 |
| 2 | 定义可扩展目标 |
| 3 | 应用缩放策略 |
| 4 | 发送流量到端点 |
| 5 | 监控指标并调整实例数量 |
| 6 | 删除资源 |
构建端到端机器学习工作流与优化预测成本性能
13. 部署多模型端点
多模型端点是处理大量模型时非常有用的技术。在 SageMaker 中,多模型端点允许在单个端点上托管多个模型,根据请求动态加载和卸载模型,从而节省资源和成本。
以下是部署多模型端点的一般步骤:
1. 准备模型 :将训练好的模型保存到 S3 存储桶中,每个模型一个文件夹。
2. 创建模型包 :为每个模型创建模型包,包含模型的元数据和推理代码。
3. 创建多模型端点配置 :指定端点的实例类型、初始实例数量等参数。
4. 创建多模型端点 :使用端点配置创建多模型端点。
以下是一个简单的示例代码:
import boto3
sm = boto3.client('sagemaker')
# 准备模型
model_data_url = 's3://your-bucket/models/'
# 创建模型包
model_package_group_name = 'multi-model-package-group'
model_package = sm.create_model_package(
ModelPackageGroupName=model_package_group_name,
ModelPackageDescription='Multi-model package',
InferenceSpecification={
'Containers': [
{
'Image': 'your-inference-image',
'ModelDataUrl': model_data_url
}
],
'SupportedContentTypes': ['text/plain'],
'SupportedResponseTypes': ['application/json']
}
)
# 创建多模型端点配置
endpoint_config_name = 'multi-model-epc'
endpoint_config = sm.create_endpoint_config(
EndpointConfigName=endpoint_config_name,
ProductionVariants=[
{
'VariantName': 'multi-model-variant',
'ModelName': model_package['ModelPackageArn'],
'InitialInstanceCount': 1,
'InstanceType': 'ml.m5.xlarge'
}
]
)
# 创建多模型端点
endpoint_name = 'multi-model-ep'
sm.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=endpoint_config_name
)
14. 使用 Amazon Elastic Inference 部署模型
Amazon Elastic Inference 允许在不使用昂贵的 GPU 实例的情况下,为推理工作负载添加 GPU 加速。通过将 Elastic Inference 加速器附加到 CPU 实例上,可以在降低成本的同时提高推理性能。
以下是使用 Amazon Elastic Inference 部署模型的步骤:
1. 选择合适的 Elastic Inference 加速器类型 :根据模型的大小和推理需求选择合适的加速器类型。
2. 创建模型 :指定使用的 Elastic Inference 加速器类型。
3. 部署模型 :将模型部署到带有 Elastic Inference 加速器的端点上。
以下是一个示例代码:
from sagemaker import Model
from sagemaker import image_uris
# 选择 Elastic Inference 加速器类型
ei_type = 'ei.c5.large'
# 创建模型
container = image_uris.retrieve(
'your-algorithm',
'your-region')
model = Model(
image_uri=container,
model_data='s3://your-bucket/model.tar.gz',
role='your-role',
sagemaker_session='your-session',
name='your-model-name',
vpc_config=None,
enable_network_isolation=False,
predictor_cls=None,
model_server_workers=None,
entry_point=None,
source_dir=None,
dependencies=None,
env=None,
code_location=None,
image_config=None,
container_log_level=None,
container_defs=None,
volume_size=None,
instance_type='ml.m5.xlarge',
accelerator_type=ei_type
)
# 部署模型
endpoint_name = 'your-endpoint-name'
model.deploy(
initial_instance_count=1,
instance_type='ml.m5.xlarge',
endpoint_name=endpoint_name
)
15. 使用 Amazon SageMaker Neo 编译模型
Amazon SageMaker Neo 可以将训练好的模型编译为针对特定硬件平台优化的格式,从而提高推理性能和降低成本。
以下是使用 Amazon SageMaker Neo 编译模型的步骤:
1. 准备模型 :将训练好的模型保存到 S3 存储桶中。
2. 指定目标平台 :选择要优化的硬件平台,如 AWS Inferentia、NVIDIA GPU 等。
3. 编译模型 :使用 SageMaker Neo 编译模型。
4. 部署编译后的模型 :将编译后的模型部署到端点上。
以下是一个示例代码:
import boto3
sm = boto3.client('sagemaker')
# 准备模型
model_data_url = 's3://your-bucket/model.tar.gz'
# 指定目标平台
target_platform = {
'Os': 'LINUX',
'Arch': 'X86_64',
'Accelerator': 'NVIDIA'
}
# 编译模型
compilation_job_name = 'your-compilation-job-name'
compilation_job = sm.create_compilation_job(
CompilationJobName=compilation_job_name,
RoleArn='your-role-arn',
InputConfig={
'S3Uri': model_data_url,
'DataInputConfig': '{"input": [1, 3, 224, 224]}',
'Framework': 'TENSORFLOW'
},
OutputConfig={
'S3OutputLocation': 's3://your-bucket/compiled-model/',
'TargetPlatform': target_platform
},
StoppingCondition={
'MaxRuntimeInSeconds': 900
}
)
# 等待编译完成
import time
while True:
job_status = sm.describe_compilation_job(CompilationJobName=compilation_job_name)
if job_status['CompilationJobStatus'] in ['COMPLETED', 'FAILED']:
break
time.sleep(10)
# 部署编译后的模型
if job_status['CompilationJobStatus'] == 'COMPLETED':
compiled_model_data_url = job_status['ModelArtifacts']['S3ModelArtifacts']
# 创建模型和端点的代码与之前类似
16. 总结与展望
通过使用 Amazon SageMaker Pipelines 构建端到端的机器学习工作流,以及利用自动缩放、多模型端点、Elastic Inference 和 SageMaker Neo 等技术优化预测成本和性能,我们可以更高效地开发和部署机器学习模型。
在实际应用中,需要根据具体的业务需求和数据特点选择合适的技术和工具。同时,不断关注 AWS 提供的新功能和优化方案,以进一步提升模型的性能和降低成本。
多模型端点部署步骤表格
| 步骤 | 操作 |
|---|---|
| 1 | 准备模型到 S3 存储桶 |
| 2 | 创建模型包 |
| 3 | 创建多模型端点配置 |
| 4 | 创建多模型端点 |
模型优化技术流程图
graph LR
A[准备模型] --> B[选择优化技术]
B --> C{技术类型}
C --> |多模型端点| D[部署多模型端点]
C --> |Elastic Inference| E[使用 EI 部署模型]
C --> |SageMaker Neo| F[编译模型并部署]
通过以上的技术和方法,我们可以构建高效、低成本的机器学习预测基础设施,满足不同业务场景的需求。在未来的机器学习开发中,合理运用这些技术将成为提升竞争力的关键。
利用 Amazon SageMaker 构建 ML 工作流并优化成本
超级会员免费看
3448

被折叠的 条评论
为什么被折叠?



