如何调度SageMaker端点启停?调用update_endpoint报错求助
SageMaker端点启停解决方案
先解决你的语法错误
你遇到的cannot assign to operator语法错误,大概率是代码中存在笔误——比如把赋值符号=误写成了比较运算符==。检查第6行代码,确保是desired_status = 'OutOfService'而非desired_status == 'OutOfService'。不过即使修正这个错误,DesiredStatus='OutOfService'也无法实现停止端点的目的,这个参数用于端点部署状态的管理,并非停止端点的正确方式。
正确的端点启停方法
方法1:直接使用StopEndpoint/StartEndpoint API(推荐)
AWS提供了专门的启停API,操作简洁且无需修改实例数或端点配置:
停止端点
import boto3 client = boto3.client('sagemaker') endpoint_name = 'my-endpoint' # 停止端点 response = client.stop_endpoint(EndpointName=endpoint_name) print(response)
启动端点
import boto3 client = boto3.client('sagemaker') endpoint_name = 'my-endpoint' # 启动端点 response = client.start_endpoint(EndpointName=endpoint_name) print(response)
执行后端点状态会分别变为Stopped和InService,无需额外管理实例数或配置。
方法2:调整实例数至0(停止)/恢复实例数(启动)
如果无法使用上述API(比如旧版本SDK),可以通过调整端点变体的实例数来实现启停:
停止端点
import boto3 client = boto3.client('sagemaker') endpoint_name = 'my-endpoint' # 获取端点的变体名称 endpoint_desc = client.describe_endpoint(EndpointName=endpoint_name) variant_name = endpoint_desc['ProductionVariants'][0]['VariantName'] # 将实例数设为0 response = client.update_endpoint_weights_and_capacities( EndpointName=endpoint_name, DesiredWeightsAndCapacities=[ { 'VariantName': variant_name, 'DesiredInstanceCount': 0 } ] ) print(response)
启动端点
import boto3 client = boto3.client('sagemaker') endpoint_name = 'my-endpoint' # 获取端点的变体名称 endpoint_desc = client.describe_endpoint(EndpointName=endpoint_name) variant_name = endpoint_desc['ProductionVariants'][0]['VariantName'] # 恢复实例数为所需数量(示例为1) response = client.update_endpoint_weights_and_capacities( EndpointName=endpoint_name, DesiredWeightsAndCapacities=[ { 'VariantName': variant_name, 'DesiredInstanceCount': 1 } ] ) print(response)
方法3:通过更新端点配置实现启停
这种方式需要创建新的端点配置,将实例数设为0(停止)或恢复实例数(启动),再更新端点使用新配置:
停止端点
import boto3 import time client = boto3.client('sagemaker') endpoint_name = 'my-endpoint' # 获取当前端点配置信息 endpoint_desc = client.describe_endpoint(EndpointName=endpoint_name) endpoint_config_name = endpoint_desc['EndpointConfigName'] config_desc = client.describe_endpoint_config(EndpointConfigName=endpoint_config_name) # 生成新配置,将所有变体实例数设为0 new_variants = [] for variant in config_desc['ProductionVariants']: new_variant = variant.copy() new_variant['InitialInstanceCount'] = 0 new_variants.append(new_variant) # 创建新的端点配置 new_config_name = f"{endpoint_config_name}-stopped-{int(time.time())}" client.create_endpoint_config( EndpointConfigName=new_config_name, ProductionVariants=new_variants ) # 更新端点使用新配置 client.update_endpoint( EndpointName=endpoint_name, EndpointConfigName=new_config_name )
启动端点
只需将上述代码中的InitialInstanceCount设回原实例数,创建新配置后更新端点即可。
内容的提问来源于stack exchange,提问作者Ankita Chandel
相关产品推荐
相关产品推荐

