AWS Sagemaker PySparkProcessor 可以通过指定实例计数和实例类型来控制处理集群的大小。但是,它目前没有默认的自动扩缩容功能。但是,可以使用AWS Autoscaling 来进行自动扩缩容操作。
以下是一个使用 AWS Sagemaker PySparkProcessor 和 AWS Autoscaling 的示例代码:
import boto3
import sagemaker
from sagemaker import get_execution_role
from sagemaker.spark.processing import PySparkProcessor
from sagemaker.autoscaling import CronJobScheduler
# 获取角色
role = get_execution_role()
# 获取Sagemaker session 和 s3 bucket
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
# 创建 S3 input 和 output路径
input_prefix = 'input'
input_uri = f's3://{bucket}/{input_prefix}/'
output_prefix = 'output'
output_uri = f's3://{bucket}/{output_prefix}/'
# 将 PySpark 脚本上传到s3
code_path = 'scripts'
code_uri = f's3://{bucket}/code/'
sagemaker_session.upload_data(path=code_path, bucket=bucket, key_prefix='code')
code_uri = sagemaker_session.upload_data(path=code_path, bucket=bucket, key_prefix='code')
# 配置自动扩缩容
autoscaling = boto3.client('autoscaling')
desired_size = 1
autoscaling_params = {'AutoScalingGroupName': 'processing-group',
'ScheduledActionName': 'scale-out',
'DesiredCapacity': desired_size}
# 每分钟进行自动扩容一次
scheduler = CronJobScheduler(
scheduled_action_name='scale-out',
target_min_capacity=1,
target_max_capacity=4,
role_arn=role,
scheduled_expression='* * * * ? *'
)
with scheduler:
# 创建 PySparkProcessor
processor = PySparkProcessor(base_job_name='processing-jobs',
framework_version='2.4',
role=role,
instance_count=1,
instance_type='ml.m5.xlarge',
max_runtime_in_seconds=1200) # 20 minutes
# 开始处理任务
processor.run(spark_event_logs_uri=input_uri,
logs=True,
arguments=['--output', output_uri, '--job-id', '6690', '--model-version', 'v1'])
此代码创建了一个名为 processing-group
的 Auto Scaling Group 对象,并使用 ScheduledAction
扩展这个组的实