ai newsFr., 23. Okt.
EilmeldungMoonshot releases Kimi K3.1 Pro and says it cut its hacking skills

Auto Scaling fuer SageMaker-AI-Endpoints mit AWS CDK automatisieren

Wenn Application Auto Scaling an einem SageMaker-AI-Endpoint registriert ist, schlagen Deployments ueber CloudFormation und AWS CDK fehl. Ein wiederverwendbarer CDK-Construct mit CloudFormation Custom Resources meldet Auto Scaling automatisch ab und wieder an.

AWS ML BlogFreitag 18:30 · 23.10.DE8 Min. Lesezeit
Bild: AWS ML Blog

Die Aktualisierung der Echtzeit-Endpunkt-Konfiguration von Amazon SageMaker AI (Änderung des Instanztyps, der Instanzanzahl oder der Umgebungsvariablen) führt dazu, dass Deployments über AWS CloudFormation oder das AWS Cloud Development Kit (AWS CDK) fehlschlagen. SageMaker AI verlangt, dass Sie das skalierbare Ziel vor der Aktualisierung des Endpunkts abmelden. Wenn Sie es jedoch abmelden, kann CloudFormation die AWS Application Auto Scaling Ressourcen nicht mehr nachverfolgen.

In diesem Beitrag zeigen wir Ihnen, wie Sie mithilfe eines wiederverwendbaren CDK-Constructs mit AWS CloudFormation Custom Resources das Abmelden und Anmelden von Auto Scaling während Endpunkt-Aktualisierungen automatisch orchestrieren. Sie können Ihre Endpunkt-Konfiguration und Auto Scaling Parameter in einem einzigen Deployment aktualisieren, ohne dass ein manuelles Eingreifen erforderlich ist.

Wenn Sie einen SageMaker AI Endpunkt mit nativen CloudFormation Auto Scaling Ressourcen bereitstellen und anschließend die Endpunkt-Konfiguration ändern und erneut bereitstellen, treten mehrere Fehlerarten auf. Welcher Fehler konkret auftritt, hängt davon ab, was Sie ändern und wie Sie das Problem umgehen.

CloudFormation versucht, den Endpunkt zu aktualisieren, während das skalierbare Ziel noch angemeldet ist. SageMaker AI weist die Aktualisierung mit folgender Fehlermeldung ab:

Die Variante(n) "[AllTraffic]" müssen als skalierbare Ziele bei Application Auto Scaling abgemeldet werden, bevor sie entfernt oder ihr Instanztyp aktualisiert werden kann. SageMaker AI blockiert die Endpunkt-Aktualisierung, bevor CloudFormation die Auto Scaling Ressourcen erreicht.

Wenn Sie das skalierbare Ziel über die AWS Command Line Interface (AWS CLI) abmelden und erneut bereitstellen, wobei nur die Endpunkt-Konfiguration geändert wurde, ist das Deployment erfolgreich. CloudFormation meldet jedoch keine Auto Scaling Ressourcen an, obwohl sie in der CloudFormation Template vorhanden sind. Da sich die Auto Scaling Parameter in der CloudFormation Template nicht geändert haben, meldet CloudFormation weder das skalierbare Ziel an, noch wendet es die Scaling-Richtlinie erneut an. Der Endpunkt läuft nun ohne Auto Scaling, und es gibt keinen Fehler, der darauf hinweist, dass etwas schiefgelaufen ist.

Wenn Sie das skalierbare Ziel über die AWS CLI abmelden und mit Änderungen an den Auto Scaling Parametern erneut bereitstellen, versucht CloudFormation, die Ressource ScalableTarget zu aktualisieren, die nicht mehr existiert:

Die Ressource vom Typ 'AWS::ApplicationAutoScaling::ScalableTarget' mit der Kennung 'endpoint/<name>/variant/AllTraffic|sagemaker:variant:DesiredInstanceCount|sagemaker' wurde nicht gefunden. Dieser Fehler ist besonders deshalb bemerkenswert, weil auch das Rollback fehlschlägt (UPDATE_ROLLBACK_FAILED), sodass der Stack in einem defekten Zustand verbleibt, der ein manuelles Eingreifen in der CloudFormation Konsole erfordert.

Sie können diesen CDK-Construct verwenden, um die nativen CloudFormation Ressourcen AWS::ApplicationAutoScaling::ScalableTarget und AWS::ApplicationAutoScaling::ScalingPolicy durch drei Custom Resources zu ersetzen. Diese Custom Resources melden Auto Scaling um die Endpunkt-Aktualisierung herum ab und wieder an, mit einer expliziten Abhängigkeitsreihenfolge, die durch node.add_dependency Aufrufe in CDK erzwungen wird. Die vollständige Abfolge lautet:

Abbildung 1: Orchestrierung der SageMaker AI Endpunkt-Auto Scaling durch Custom Resources rund um eine CDK-verwaltete Endpunkt-Aktualisierung.

Register Scalable Target und Attach Scaling Policy verwenden das asynchrone Abschlussmuster des CDK Providers. Jede Custom Resource verfügt über einen on_event Handler, der sofort zurückkehrt, und einen is_complete Handler. Der Waiter des Providers ruft den is_complete Handler in einem Intervall (alle 30 Sekunden) erneut auf, bis seine Bereitschaftsprüfung erfolgreich ist. Der total_timeout des Providers (1 Stunde für Register Scalable Target, 15 Minuten für Attach Scaling Policy) begrenzt die Wartezeit, sodass diese nicht durch das Timeout eines einzelnen Lambda Aufrufs eingeschränkt ist.

Eine Eigenschaft ConfigHash auf jeder Custom Resource erzwingt, dass CloudFormation die Lambda Funktionen erneut aufruft, sobald sich ein Konfigurationswert ändert. Die Endpunkt-Konfiguration und die Auto Scaling Parameter werden gemeinsam definiert, weil ein einziger ConfigHash die Auto Scaling Orchestrierung steuert.

Obwohl der Construct drei Custom Resources definiert, enthält der bereitgestellte Stack mehr als drei Lambda Funktionen. Jede Custom Resource wird von einem CDK cr.Provider unterstützt, und das Provider-Framework erzeugt seine eigenen Hilfs-Lambda-Funktionen. Ein synchroner Provider (Deregister) ergänzt eine Framework-Funktion.

Ein asynchroner Provider (Register Scalable Target und Attach Scaling Policy) ergänzt drei Funktionen (onEvent, isComplete und onTimeout) sowie eine AWS Step Functions State Machine, die den Waiter antreibt. Der bereitgestellte Stack enthält daher drei Custom Resources, zwei Step Functions State Machines und zwölf Lambda Funktionen. Fünf dieser Ressourcen enthalten den eigenen Handler-Code des Constructs (eine für Deregister sowie ein on_event und is_complete Paar für jede asynchrone Ressource), während die übrigen sieben vom Provider-Framework generiert werden.

Sie schreiben oder pflegen die vom Framework generierten Funktionen nicht, doch sie sind im Stack vorhanden und sollten bei der Überprüfung der bereitgestellten Ressourcen berücksichtigt werden.

In dieser Anleitung stellen Sie einen SageMaker AI Endpunkt mit Auto Scaling mithilfe des bereitgestellten Beispiel-Stacks bereit und prüfen anschließend, ob Konfigurationsaktualisierungen korrekt funktionieren.

Die Anleitung umfasst die folgenden Schritte:

Der Quellcode ist im verlinkten GitHub Repository verfügbar.

Für diese Anleitung benötigen Sie Folgendes:

git clone https://github.com/aws-samples/sample-sagemaker-endpoint-autoscaling.git cd sample-sagemaker-endpoint-autoscaling Installieren Sie die Abhängigkeiten: uv sync Konfigurieren Sie Ihre Endpunkt- und Auto Scaling Einstellungen. Die Endpunkt- und Auto Scaling Einstellungen werden gemeinsam in config/config.yaml definiert, weil ein einzelner config_hash die Auto Scaling Orchestrierung steuert. Eine Änderung in einem der beiden Abschnitte löst die vollständige Abfolge aus.

Bearbeiten Sie config/config.yaml mit Ihren Werten:

endpoint: endpoint_name: "my-model-endpoint" image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-model:latest" model_data_url: "s3://my-bucket/models/model.tar.gz" instance_type: "ml.m5.large" initial_instance_count: 1 environment: {} autoscaling: min_capacity: 1 max_capacity: 10 target_value: 100 scale_in_cooldown: 600 scale_out_cooldown: 120 Die Endpunkt-Parameter entsprechen den SageMaker AI APIs CreateModel und CreateEndpointConfig. Die Auto Scaling Parameter entsprechen den Application Auto Scaling APIs RegisterScalableTarget und PutScalingPolicy.

uv run cdk bootstrap Stellen Sie den Stack bereit: uv run cdk deploy InferenceStack CloudFormation erstellt das SageMaker AI Modell, die Endpunkt-Konfiguration und den Endpunkt und führt anschließend die drei Custom Resources nacheinander aus, um Auto Scaling anzumelden.

aws application-autoscaling describe-scalable-targets --service-namespace sagemaker --resource-ids endpoint/my-model-endpoint/variant/AllTraffic Prüfen Sie, ob das Deployment die Scaling-Richtlinie angewendet hat: aws application-autoscaling describe-scaling-policies --service-namespace sagemaker --resource-id endpoint/my-model-endpoint/variant/AllTraffic Testen Sie eine Aktualisierung. Ändern Sie einen Wert in config/config.yaml, zum Beispiel den Instanztyp von ml.m5.large zu ml.m5.xlarge, und stellen Sie erneut bereit:

uv run cdk deploy InferenceStack Nach Abschluss des Deployments prüfen Sie, ob Auto Scaling weiterhin angemeldet ist und die aktualisierten Werte enthält:

aws application-autoscaling describe-scalable-targets --service-namespace sagemaker --resource-ids endpoint/my-model-endpoint/variant/AllTraffic Integration in einen bestehenden Stack. Verwenden Sie den Beispiel-Stack, wenn Sie neu starten oder eine Referenzimplementierung wünschen. Verwenden Sie den Construct direkt, wenn Sie bereits einen CDK Stack mit SageMaker AI Ressourcen besitzen.

Zur Integration in einen bestehenden Stack kopieren Sie das Verzeichnis sagemaker_autoscaling/constructs/ in Ihr Projekt und fügen den Construct neben Ihren Endpunkt-Ressourcen hinzu:

import json from sagemaker_autoscaling.constructs.sagemaker_autoscaling_construct import ( AutoscalingConfig, SagemakerAutoscalingConstruct, SagemakerAutoscalingProps, ) # Sowohl Endpunkt- als auch Auto Scaling Werte müssen in config_hash enthalten sein, damit # eine Änderung in einem der beiden Bereiche die Auto Scaling Orchestrierung auslöst. config_hash = json.dumps({ "endpoint": { "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-model:latest", "modelDataUrl": "s3://my-bucket/models/model.tar.gz", "instanceType": "ml.m5.large", "initialInstanceCount": 1, }, "autoscaling": { "minCapacity": 1, "maxCapacity": 10, "targetValue": 100, "scaleInCooldown": 600, "scaleOutCooldown": 120, }, }) SagemakerAutoscalingConstruct( self, "Autoscaling", props=SagemakerAutoscalingProps( endpoint=your_endpoint, # your CfnEndpoint autoscaling=AutoscalingConfig( min_capacity=1, max_capacity=10, target_value=100, scale_in_cooldown=600, scale_out_cooldown=120, ), config_hash=config_hash, ), ) Funktionsweise des Constructs. Dieser Abschnitt erläutert die wichtigsten Implementierungsdetails von SagemakerAutoscalingConstruct.

Die Custom Resource Deregister ruft deregister_scalable_target vor der Endpunkt-Aktualisierung auf. Sie behandelt die ObjectNotFoundException bei Erstdeployments, bei denen noch kein skalierbares Ziel existiert:

def handler(event, context): resource_id = event["ResourceProperties"]["ResourceId"] if event["RequestType"] in ("Create", "Update"): try: client.deregister_scalable_target( ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", ) except client.exceptions.ObjectNotFoundException: pass # Kein skalierbares Ziel beim ersten Deployment return {"PhysicalResourceId": f"deregister-{resource_id}"} Die Abhängigkeit wird in CDK eingerichtet:

props.endpoint.node.add_dependency(deregister) Skalierbares Ziel registrieren Auch wenn CloudFormation die Endpunkt-Ressource als abgeschlossen behandelt, sobald das Update akzeptiert wurde, kann das skalierbare Ziel erst registriert werden, nachdem der Endpunkt den Status InService erreicht hat. Statt einen einzelnen Lambda-Aufruf auf diese Wartezeit zu blockieren, nutzt Register Scalable Target das asynchrone Abschlussmuster des Providers. Der on_event Handler kehrt sofort zurück, und der Waiter des Providers ruft den is_complete Handler im Abstand von query_interval erneut auf, bis der Endpunkt InService ist. Der total_timeout des Providers (1 Stunde) begrenzt die Wartezeit, nicht das Timeout eines einzelnen Lambda-Aufrufs:

def handler(event, context): props = event["ResourceProperties"] resource_id = props["ResourceId"] endpoint_name = resource_id.split("/") if event["RequestType"] == "Delete": return {"IsComplete": True} status = sm_client.describe_endpoint(EndpointName=endpoint_name)["EndpointStatus"] if status == "Failed": raise Exception("Endpoint in Failed state") if status!= "InService": return {"IsComplete": False} as_client.register_scalable_target( ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", MinCapacity=int(props["MinCapacity"]), MaxCapacity=int(props["MaxCapacity"]), ) return {"IsComplete": True} Beim Löschen des Stacks deregistriert der on_event Handler das skalierbare Ziel, um aufzuräumen.

Es gibt ein kurzes Zeitfenster, nachdem RegisterScalableTarget zurückkehrt, in dem das Ziel noch nicht abfragbar ist. Attach Scaling Policy verwendet dasselbe asynchrone Abschlussmuster: Der on_event Handler kehrt sofort zurück, und der is_complete Handler meldet den Abschluss erst, sobald das skalierbare Ziel abfragbar ist; zu diesem Zeitpunkt wendet er die Richtlinie an. Der total_timeout des Providers (15 Minuten) begrenzt die Wartezeit:

def handler(event, context): props = event["ResourceProperties"] resource_id = props["ResourceId"] if event["RequestType"] == "Delete": return {"IsComplete": True} resp = client.describe_scalable_targets( ServiceNamespace="sagemaker", ResourceIds=[resource_id], ScalableDimension="sagemaker:variant:DesiredInstanceCount", ) if not resp.get("ScalableTargets"): return {"IsComplete": False} client.put_scaling_policy( PolicyName=props["PolicyName"], ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", PolicyType="TargetTrackingScaling", TargetTrackingScalingPolicyConfiguration=json.loads(props["ScalingPolicyConfig"]), ) return {"IsComplete": True} Beim Löschen des Stacks löscht der on_event Handler die Skalierungsrichtlinie, um aufzuräumen.

Um künftige Kosten zu vermeiden, löschen Sie die Ressourcen:

uv run cdk destroy InferenceStack Dies entfernt den SageMaker AI Endpunkt, die Endpunkt-Konfiguration, das Modell, die Lambda-Funktionen, die IAM-Rollen, die von der Target-Tracking-Skalierungsrichtlinie erstellten Amazon CloudWatch Alarme, und deregistriert das skalierbare Ziel.

In diesem Beitrag haben wir gezeigt, wie man mit einem wiederverwendbaren CDK Construct Auto Scaling automatisch deregistriert und registriert, um SageMaker AI Endpunkt-Updates zu orchestrieren. Das Construct verwendet drei CloudFormation Custom Resources mit expliziter Abhängigkeitsreihenfolge und einer ConfigHash-Eigenschaft, um Auto Scaling über Deployments hinweg intakt zu halten.

Um loszulegen, klonen Sie das Repository sample-sagemaker-endpoint-autoscaling und folgen Sie den Setup-Anweisungen. Das Repository enthält einen Beispiel-Stack, den Sie direkt deployen können, oder Sie integrieren das Construct in Ihren bestehenden CDK Stack.

Weitere Informationen zu Application Auto Scaling für SageMaker AI finden Sie unter Automatically scale Amazon SageMaker AI models. Weitere Informationen zu CloudFormation Custom Resources finden Sie unter Custom resources im AWS CloudFormation User Guide.

Lauren ist Associate Delivery Consultant bei Amazon Web Services mit dem Schwerpunkt AI/ML. Sie arbeitet mit Kundenteams daran, Machine-Learning- und Generative-AI-Lösungen zu entwerfen, zu entwickeln, zu deployen und zu skalieren. Sie hat einen B.S. in Data Science & Analytics und einen M.S. in Computer Science von der Case Western Reserve University.

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

Updating the Amazon Sagemaker AI real-time endpoint configuration (changing the instance type, instance count, or environment variables) causes deployments through AWS CloudFormation or the AWS Cloud Development Kit (AWS CDK) to fail. SageMaker AI requires you to deregister the scalable target before updating the endpoint, but when you deregister it, CloudFormation can’t track the AWS Application Auto Scaling resources.

In this post, we show you how to use a reusable CDK construct with AWS CloudFormation custom resources to orchestrate deregister and register auto scaling automatically during endpoint updates. You can update your endpoint configuration and auto scaling parameters in a single deployment without manual intervention.

When you deploy a SageMaker AI endpoint with native CloudFormation auto scaling resources, then change the endpoint configuration and redeploy, several failure modes emerge. The specific failure depends on what you change and how you work around the issue.

CloudFormation tries to update the endpoint while the scalable target is still registered. SageMaker AI rejects the update with the following error:

The variant(s) "[AllTraffic]" must be deregistered as scalable targets with Application Auto Scaling before they can be removed or have their instance type updated. SageMaker AI blocks the endpoint update before CloudFormation reaches the auto scaling resources.

If you deregister the scalable target through the AWS Command Line Interface (AWS CLI) and redeploy with only an endpoint configuration change, the deployment succeeds. However, CloudFormation doesn’t register auto scaling even though it is in the CloudFormation template. Because the auto scaling parameters in the CloudFormation template haven’t changed, CloudFormation doesn’t register the scalable target or re-apply the scaling policy. The endpoint is now running without auto scaling, and there is no error to indicate anything went wrong.

If you deregister the scalable target through the AWS CLI and redeploy with auto scaling parameter changes, CloudFormation tries to update the ScalableTarget resource that no longer exists:

Resource of type 'AWS::ApplicationAutoScaling::ScalableTarget' with identifier 'endpoint/<name>/variant/AllTraffic|sagemaker:variant:DesiredInstanceCount|sagemaker' was not found. This failure is notable because the rollback also fails (UPDATE_ROLLBACK_FAILED), leaving the stack in a broken state that requires manual intervention in the CloudFormation console to recover.

You can use this CDK construct to replace the native AWS::ApplicationAutoScaling::ScalableTarget and AWS::ApplicationAutoScaling::ScalingPolicy CloudFormation resources with three custom resources. These custom resources deregister and register auto scaling around the endpoint update with explicit dependency ordering, enforced by node.add_dependency calls in CDK. The full sequence is:

Figure 1: Custom resource orchestration of SageMaker AI endpoint auto scaling around a CDK-managed endpoint update.

Register Scalable Target and Attach Scaling Policy use the CDK provider’s asynchronous completion pattern. Each custom resource has an on_event handler that returns immediately and an is_complete handler. The provider’s waiter re-invokes the is_complete handler on an interval (every 30 seconds) until its readiness check passes. The provider’s total_timeout (1 hour for Register Scalable Target, 15 minutes for Attach Scaling Policy) bounds the wait, so it isn’t limited by the timeout of any single Lambda invocation.

A ConfigHash property on each custom resource forces CloudFormation to re-invoke the Lambda functions whenever a configuration value changes. The endpoint configuration and auto scaling parameters are defined together because a single ConfigHash drives the auto scaling orchestration.

While the construct defines three custom resources, the deployed stack contains more than three Lambda functions. Each custom resource is backed by a CDK cr.Provider, and the provider framework generates its own helper Lambda functions. A synchronous provider (Deregister) adds one framework function.

An asynchronous provider (Register Scalable Target and Attach Scaling Policy) adds three ( onEvent, isComplete, and onTimeout ) plus an AWS Step Functions state machine that drives the waiter. As a result, the deployed stack contains three custom resources, two Step Functions state machines, and twelve Lambda functions. Five of the resources hold the construct’s own handler code (one for Deregister, and an on_event and is_complete pair for each asynchronous resource), with the remaining seven generated by the provider framework.

You don’t write or maintain the framework-generated functions, but they are present in the stack and worth accounting for when you review the deployed resources.

In this walkthrough, you deploy a SageMaker AI endpoint with auto scaling using the provided example stack, then verify that configuration updates work correctly.

The walkthrough includes the following steps:

The source code is available in the linked GitHub repository.

For this walkthrough, you need the following:

git clone https://github.com/aws-samples/sample-sagemaker-endpoint-autoscaling.git cd sample-sagemaker-endpoint-autoscaling Install dependencies: uv sync Configure your endpoint and auto scaling settings The endpoint and auto scaling settings are defined together in config/ config.yaml because a single config_hash drives the auto scaling orchestration. A change to either section triggers the full sequence.

Edit config/ config.yaml with your values:

endpoint: endpoint_name: "my-model-endpoint" image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-model:latest" model_data_url: "s3://my-bucket/models/model.tar.gz" instance_type: "ml.m5.large" initial_instance_count: 1 environment: {} autoscaling: min_capacity: 1 max_capacity: 10 target_value: 100 scale_in_cooldown: 600 scale_out_cooldown: 120 The endpoint parameters map to the SageMaker AI CreateModel and CreateEndpointConfig APIs. The auto scaling parameters map to the Application Auto Scaling RegisterScalableTarget and PutScalingPolicy APIs.

uv run cdk bootstrap Deploy the stack: uv run cdk deploy InferenceStack CloudFormation creates the SageMaker AI model, endpoint configuration, and endpoint, then runs the three custom resources in sequence to register auto scaling.

aws application-autoscaling describe-scalable-targets --service-namespace sagemaker --resource-ids endpoint/my-model-endpoint/variant/AllTraffic Verify that the deployment applied the scaling policy: aws application-autoscaling describe-scaling-policies --service-namespace sagemaker --resource-id endpoint/my-model-endpoint/variant/AllTraffic Test an update Change a value in config/ config.yaml, for example, update the instance type from ml.m5.large to ml.m5.xlarge, and redeploy:

uv run cdk deploy InferenceStack After the deployment completes, verify that auto scaling is still registered and has the updated values:

aws application-autoscaling describe-scalable-targets --service-namespace sagemaker --resource-ids endpoint/my-model-endpoint/variant/AllTraffic Integrating with an existing stack Use the example stack if you’re starting fresh or want a reference implementation. Use the construct directly if you already have a CDK stack with SageMaker AI resources.

To integrate with an existing stack, copy the sagemaker_autoscaling/constructs/ directory into your project and add the construct alongside your endpoint resources:

import json from sagemaker_autoscaling.constructs.sagemaker_autoscaling_construct import ( AutoscalingConfig, SagemakerAutoscalingConstruct, SagemakerAutoscalingProps, ) # Both endpoint and auto scaling values must be in config_hash so that # a change to either triggers the auto scaling orchestration. config_hash = json.dumps({ "endpoint": { "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-model:latest", "modelDataUrl": "s3://my-bucket/models/model.tar.gz", "instanceType": "ml.m5.large", "initialInstanceCount": 1, }, "autoscaling": { "minCapacity": 1, "maxCapacity": 10, "targetValue": 100, "scaleInCooldown": 600, "scaleOutCooldown": 120, }, }) SagemakerAutoscalingConstruct( self, "Autoscaling", props=SagemakerAutoscalingProps( endpoint=your_endpoint, # your CfnEndpoint autoscaling=AutoscalingConfig( min_capacity=1, max_capacity=10, target_value=100, scale_in_cooldown=600, scale_out_cooldown=120, ), config_hash=config_hash, ), ) How the construct works This section walks through the key implementation details of SagemakerAutoscalingConstruct.

The Deregister custom resource calls deregister_scalable_target before the endpoint update. It handles ObjectNotFoundException for first deployments where no scalable target exists:

def handler(event, context): resource_id = event["ResourceProperties"]["ResourceId"] if event["RequestType"] in ("Create", "Update"): try: client.deregister_scalable_target( ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", ) except client.exceptions.ObjectNotFoundException: pass # No scalable target on first deploy return {"PhysicalResourceId": f"deregister-{resource_id}"} The dependency is established in CDK:

props.endpoint.node.add_dependency(deregister) Register Scalable Target Even though CloudFormation treats the endpoint resource as complete once the update is accepted, the scalable target can only be registered after the endpoint reaches InService. Rather than block a single Lambda invocation on that wait, Register Scalable Target uses the provider’s asynchronous completion pattern. The on_event handler returns immediately, and the provider’s waiter re-invokes the is_complete handler on query_interval until the endpoint is InService. The provider’s total_timeout (1 hour) bounds the wait, not the timeout of any single Lambda invocation:

def handler(event, context): props = event["ResourceProperties"] resource_id = props["ResourceId"] endpoint_name = resource_id.split("/") if event["RequestType"] == "Delete": return {"IsComplete": True} status = sm_client.describe_endpoint(EndpointName=endpoint_name)["EndpointStatus"] if status == "Failed": raise Exception("Endpoint in Failed state") if status!= "InService": return {"IsComplete": False} as_client.register_scalable_target( ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", MinCapacity=int(props["MinCapacity"]), MaxCapacity=int(props["MaxCapacity"]), ) return {"IsComplete": True} On stack deletion, the on_event handler deregisters the scalable target to clean up.

There is a brief window after RegisterScalableTarget returns where the target isn’t yet queryable. Attach Scaling Policy uses the same asynchronous completion pattern: the on_event handler returns immediately, and the is_complete handler reports completion only once the scalable target is queryable, at which point it applies the policy. The provider’s total_timeout (15 minutes) bounds the wait:

def handler(event, context): props = event["ResourceProperties"] resource_id = props["ResourceId"] if event["RequestType"] == "Delete": return {"IsComplete": True} resp = client.describe_scalable_targets( ServiceNamespace="sagemaker", ResourceIds=[resource_id], ScalableDimension="sagemaker:variant:DesiredInstanceCount", ) if not resp.get("ScalableTargets"): return {"IsComplete": False} client.put_scaling_policy( PolicyName=props["PolicyName"], ServiceNamespace="sagemaker", ResourceId=resource_id, ScalableDimension="sagemaker:variant:DesiredInstanceCount", PolicyType="TargetTrackingScaling", TargetTrackingScalingPolicyConfiguration=json.loads(props["ScalingPolicyConfig"]), ) return {"IsComplete": True} On stack deletion, the on_event handler deletes the scaling policy to clean up.

To avoid incurring future charges, delete the resources:

uv run cdk destroy InferenceStack This removes the SageMaker AI endpoint, endpoint configuration, model, Lambda functions, IAM roles, Amazon CloudWatch alarms created by the target tracking scaling policy, and deregisters the scalable target.

In this post, we showed you how to use a reusable CDK construct to deregister and register auto scaling automatically to orchestrate SageMaker AI endpoint updates. The construct uses three CloudFormation custom resources with explicit dependency ordering and a ConfigHash property to keep auto scaling intact across deployments.

To get started, clone the sample-sagemaker-endpoint-autoscaling repository and follow the setup instructions. The repository includes an example stack you can deploy directly, or you can integrate the construct into your existing CDK stack.

For more information about Application Auto Scaling for SageMaker AI, see Automatically scale Amazon SageMaker AI models. For more information about CloudFormation custom resources, see Custom resources in the AWS CloudFormation User Guide.

Lauren is an Associate Delivery Consultant with Amazon Web Services specializing in AI/ML. She works with customer teams to design, build, deploy, and scale machine learning and generative AI solutions. She holds a B.S. in Data Science & Analytics and an M.S. in Computer Science from Case Western Reserve University.

Originaltitel: Orchestrating SageMaker AI endpoint auto scaling with AWS CDKQuelle: AWS ML Blog (AWS ML Blog). Original öffnen