diff --git a/docs/api/sagemaker_serve.rst b/docs/api/sagemaker_serve.rst index 9df8b9468c..86f4d91568 100644 --- a/docs/api/sagemaker_serve.rst +++ b/docs/api/sagemaker_serve.rst @@ -14,3 +14,11 @@ Model Deployment :show-inheritance: + +Autoscaling +----------- + +.. automodule:: sagemaker.serve.autoscaling + :members: enable_autoscaling, disable_autoscaling, describe_autoscaling, suspend_autoscaling, + resume_autoscaling, TargetTrackingPolicy, StepScalingPolicy, StepAdjustment, Alarm, + ScheduledAction, CustomMetric, ScalingTarget diff --git a/migration.md b/migration.md index 0ea3e9bef1..42ad0f1cd3 100644 --- a/migration.md +++ b/migration.md @@ -443,6 +443,7 @@ pipeline = Pipeline( | AsyncPredictor | ModelBuilder | Async inference | | JumpStartModel.benchmark_metrics / display_benchmark_metrics() / list_deployment_configs() | ModelBuilder.benchmark_metrics / display_benchmark_metrics() / list_deployment_configs() | Same names; usable on a pre-deploy JumpStart `ModelBuilder` | | snapshot_download + S3Uploader (hand-rolled) | `from sagemaker.serve import download_huggingface_model` | Downloads a Hub snapshot and optionally uploads it to S3 | +| boto3 `register_scalable_target` + `put_scaling_policy` (hand-rolled) | `from sagemaker.serve.autoscaling import enable_autoscaling, disable_autoscaling, describe_autoscaling` | Target tracking (predefined, custom or metric-math metrics), step scaling and scheduled actions on a variant's instances, an inference component's copies or a serverless endpoint's provisioned concurrency; scale to zero for inference components and asynchronous endpoints; suspend and resume | ### Processing Features @@ -504,7 +505,7 @@ pipeline = Pipeline( | Async inference | `AsyncPredictor(...)` | Via ModelBuilder.deploy | 🔄 REPLACED | | Multi-model endpoints | `MultiDataModel(...)` | Via ModelBuilder.deploy | 🔄 REPLACED | | A/B testing (multi-variant) | Production variants with traffic splitting | ProductionVariant + traffic routing | 🔄 REPLACED | -| Endpoint auto-scaling | Via boto3 Application Auto Scaling | Via ModelBuilder.deploy | 🔄 REPLACED | +| Endpoint auto-scaling | Via boto3 Application Auto Scaling | `sagemaker.serve.autoscaling.enable_autoscaling(...)` / `disable_autoscaling(...)`; `ModelBuilder.deploy(managed_instance_scaling=...)` sets an inference-component endpoint's instance bounds | 🔄 REPLACED | | Model compilation (Neo) | `Estimator.compile_model(...)` | `ModelBuilder.optimize()` | 🔄 REPLACED | ### MLOps and Workflows diff --git a/sagemaker-core/src/sagemaker/core/utils/utils.py b/sagemaker-core/src/sagemaker/core/utils/utils.py index dc6b96378d..decfe313ad 100644 --- a/sagemaker-core/src/sagemaker/core/utils/utils.py +++ b/sagemaker-core/src/sagemaker/core/utils/utils.py @@ -729,8 +729,12 @@ def _serialize_shape(value: Any) -> dict: dict: The dict of serialized shape """ serialized_dict = {} + # Keep falsy scalars such as False, 0 and "" (a MinInstanceCount of 0 is a real value). + # Drop Unassigned/None, and empty dicts and lists, so a nested shape with nothing set is + # still omitted from the request. for k, v in vars(value).items(): - if serialize_result := serialize(v): + serialize_result = serialize(v) + if serialize_result is not None and serialize_result != {} and serialize_result != []: key = snake_to_pascal(k) if is_snake_case(k) else k serialized_dict.update({key[0].upper() + key[1:]: serialize_result}) return serialized_dict diff --git a/sagemaker-core/tests/unit/generated/test_utils.py b/sagemaker-core/tests/unit/generated/test_utils.py index 4b4847eba9..ab2587bce3 100644 --- a/sagemaker-core/tests/unit/generated/test_utils.py +++ b/sagemaker-core/tests/unit/generated/test_utils.py @@ -5,6 +5,8 @@ from sagemaker.core.resources import TrainingJob, DataQualityJobDefinition from sagemaker.core.shapes import ( AdditionalS3DataSource, + ProductionVariant, + ProductionVariantManagedInstanceScaling, TrialComponent, TrialComponentParameterValue, ) @@ -401,6 +403,43 @@ def test_serialize_preserves_falsy_list_values(): assert serialize([None, "x", Unassigned(), 1]) == ["x", 1] # noqa: F405 +def test_serialize_preserves_falsy_shape_fields(): + # Regression: a shape field set to 0 or False was dropped, so e.g. a managed instance + # scaling MinInstanceCount of 0 never reached the API. + scaling = ProductionVariantManagedInstanceScaling( + status="ENABLED", min_instance_count=0, max_instance_count=2 + ) + assert serialize(scaling) == { # noqa: F405 + "Status": "ENABLED", + "MinInstanceCount": 0, + "MaxInstanceCount": 2, + } + empty_uri = AdditionalS3DataSource(s3_data_type="filestring", s3_uri="") + assert serialize(empty_uri) == { # noqa: F405 + "S3DataType": "filestring", + "S3Uri": "", + } + + +def test_serialize_still_omits_empty_nested_shapes_and_lists(): + # A nested shape with nothing set (e.g. an empty StoppingCondition) stays out of the request. + assert serialize( # noqa: F405 + ProductionVariant( + variant_name="AllTraffic", + managed_instance_scaling=ProductionVariantManagedInstanceScaling(), + ) + ) == {"VariantName": "AllTraffic"} + assert serialize(TrialComponent(trial_component_name="t", parameters={})) == { # noqa: F405 + "TrialComponentName": "t" + } + + +def test_serialize_drops_unset_shape_fields(): + assert "MaxInstanceCount" not in serialize( # noqa: F405 + ProductionVariantManagedInstanceScaling(status="ENABLED", min_instance_count=1) + ) + + def test_serialize_method_nested_shape(): trial_component_parameters = { "test_num_value": TrialComponentParameterValue(number_value=1), diff --git a/sagemaker-serve/src/sagemaker/serve/autoscaling.py b/sagemaker-serve/src/sagemaker/serve/autoscaling.py new file mode 100644 index 0000000000..a586b1c914 --- /dev/null +++ b/sagemaker-serve/src/sagemaker/serve/autoscaling.py @@ -0,0 +1,1031 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +"""Application Auto Scaling for SageMaker endpoints and inference components. + +What scales depends on the endpoint: + +* A real-time or asynchronous endpoint that hosts a model on its production variant scales the + variant's instance count (``sagemaker:variant:DesiredInstanceCount``). +* An endpoint that hosts inference components scales one component's copy count + (``sagemaker:inference-component:DesiredCopyCount``); its managed instance scaling adds or + removes the instances those copies need. +* A serverless endpoint with provisioned concurrency scales that concurrency + (``sagemaker:variant:DesiredProvisionedConcurrency``). + +A scalable target can carry any mix of target-tracking policies (on a predefined metric, a +custom CloudWatch metric, or metric math), step-scaling policies driven by a CloudWatch alarm, +and scheduled actions. Inference components and asynchronous +endpoints can also scale to zero. + +Example:: + + from sagemaker.serve.autoscaling import ( + CustomMetric, ScheduledAction, TargetTrackingPolicy, enable_autoscaling, + disable_autoscaling, + ) + + # One target-tracking policy on the default metric. + enable_autoscaling(endpoint_name="my-endpoint", min_capacity=1, max_capacity=4, target_value=4) + + # Several policies and a schedule. + enable_autoscaling( + endpoint_name="my-endpoint", + min_capacity=1, + max_capacity=8, + policies=[ + TargetTrackingPolicy(target_value=4), + TargetTrackingPolicy( + target_value=70, + metric=CustomMetric("GPUUtilization", namespace="/aws/sagemaker/Endpoints"), + name="gpu", + ), + ], + scheduled_actions=[ + ScheduledAction(name="business-hours", schedule="cron(0 8 ? * MON-FRI *)", + min_capacity=2, timezone="America/New_York"), + ], + ) + + disable_autoscaling(endpoint_name="my-endpoint") + +``enable_autoscaling`` is declarative: the policies and scheduled actions it is given are the +set this module manages on the target, so calling it again changes them and removes the ones +no longer given. It names what it creates with the ``sagemaker-sdk-`` prefix and tags the +scalable target and alarms it creates. Policies, scheduled actions, alarms and scalable targets +created any other way are left alone, and ``disable_autoscaling`` deregisters a target only when +this module registered it and nothing else is on it. +""" + +from __future__ import absolute_import + +import logging +import time +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any, Dict, List, Optional, Union + +from sagemaker.core.helper.session_helper import Session + +logger = logging.getLogger(__name__) + +SERVICE_NAMESPACE = "sagemaker" +NAME_PREFIX = "sagemaker-sdk-" +OWNER_TAG_KEY = "sagemaker-sdk:autoscaling" +OWNER_TAG_VALUE = "managed" + +VARIANT = "variant" +INFERENCE_COMPONENT = "inference-component" +PROVISIONED_CONCURRENCY = "provisioned-concurrency" + +DIMENSIONS = { + VARIANT: "sagemaker:variant:DesiredInstanceCount", + INFERENCE_COMPONENT: "sagemaker:inference-component:DesiredCopyCount", + PROVISIONED_CONCURRENCY: "sagemaker:variant:DesiredProvisionedConcurrency", +} + +#: Short names for the predefined target-tracking metrics, by kind. A full predefined metric +#: type (such as ``"SageMakerVariantInvocationsPerInstance"``) is accepted too. +METRICS = { + VARIANT: { + "concurrent-requests": "SageMakerVariantConcurrentRequestsPerModelHighResolution", + "invocations": "SageMakerVariantInvocationsPerInstance", + }, + INFERENCE_COMPONENT: { + "concurrent-requests": "SageMakerInferenceComponentConcurrentRequestsPerCopyHighResolution", + "invocations": "SageMakerInferenceComponentInvocationsPerCopy", + }, + PROVISIONED_CONCURRENCY: { + "provisioned-concurrency-utilization": "SageMakerVariantProvisionedConcurrencyUtilization", + }, +} +#: The asynchronous-endpoint metric SageMaker recommends for target tracking. +BACKLOG_PER_INSTANCE = "backlog-per-instance" + +_READ_BACK_ATTEMPTS = 6 +_READ_BACK_DELAY_SECONDS = 5 +_SCALE_OUT_FROM_ZERO = "scale-out-from-zero" + + +@dataclass +class CustomMetric: + """A CloudWatch metric to scale on, for a target-tracking policy or a step-scaling alarm. + + Args: + metric_name (str): The metric's name, such as ``"CPUUtilization"``. + namespace (str): Its namespace (default ``"AWS/SageMaker"``; instance metrics such as + ``CPUUtilization`` and ``GPUUtilization`` are in ``"/aws/sagemaker/Endpoints"``). + dimensions (dict): Dimension names to values. ``None`` (the default) uses the scaled + resource's own dimensions: ``EndpointName`` and ``VariantName`` for a variant, + ``InferenceComponentName`` for an inference component. + statistic (str): ``"Average"`` (default), ``"Sum"``, ``"Minimum"``, ``"Maximum"`` or + ``"SampleCount"``. + unit (str): The metric's unit, if it has one. + """ + + metric_name: str + namespace: str = "AWS/SageMaker" + dimensions: Optional[Dict[str, str]] = None + statistic: str = "Average" + unit: Optional[str] = None + + def _dimension_list(self, target) -> List[Dict[str, str]]: + dimensions = self.dimensions if self.dimensions is not None else target.metric_dimensions + return [{"Name": name, "Value": value} for name, value in dimensions.items()] + + +@dataclass +class TargetTrackingPolicy: + """Keep a metric near a target value by adding and removing capacity. + + Args: + target_value (float): The metric's value per instance, copy or unit of provisioned + concurrency that the policy keeps the target near. + metric: The metric to track. A short name from :data:`METRICS` for the target's kind + (``"concurrent-requests"``, the default for a real-time endpoint, or + ``"invocations"``; ``"provisioned-concurrency-utilization"`` for a serverless + endpoint; ``"backlog-per-instance"``, the default for an asynchronous endpoint), a full + predefined metric type, a :class:`CustomMetric`, or a + ``CustomizedMetricSpecification`` dict as Application Auto Scaling takes it (for + metric math). + scale_in_cooldown (int): Seconds after a scale-in before the next one (default 300). + scale_out_cooldown (int): Seconds after a scale-out before the next one (default 300). + disable_scale_in (bool): Keep the policy from removing capacity (default False). + name (str): Distinguishes this policy from the target's other target-tracking policies. + """ + + target_value: float + metric: Union[str, CustomMetric, Dict[str, Any], None] = None + scale_in_cooldown: int = 300 + scale_out_cooldown: int = 300 + disable_scale_in: bool = False + name: Optional[str] = None + + +@dataclass +class StepAdjustment: + """One step of a step-scaling policy. + + The bounds are relative to the alarm threshold: a step applies when the metric minus the + threshold falls in ``[lower_bound, upper_bound)``; ``None`` is unbounded. + """ + + scaling_adjustment: int + lower_bound: Optional[float] = None + upper_bound: Optional[float] = None + + +@dataclass +class Alarm: + """The CloudWatch alarm that drives a step-scaling policy. + + Args: + metric (CustomMetric): The metric the alarm watches. + threshold (float): The value it compares the metric with. + comparison_operator (str): Default ``"GreaterThanOrEqualToThreshold"``. + period (int): Seconds per evaluated data point (default 60). + evaluation_periods (int): Data points to evaluate (default 1). + datapoints_to_alarm (int): Breaching data points that trigger it (default all). + treat_missing_data (str): ``"missing"`` (default), ``"notBreaching"``, ``"breaching"`` or + ``"ignore"``. + """ + + metric: CustomMetric + threshold: float + comparison_operator: str = "GreaterThanOrEqualToThreshold" + period: int = 60 + evaluation_periods: int = 1 + datapoints_to_alarm: Optional[int] = None + treat_missing_data: str = "missing" + + +@dataclass +class StepScalingPolicy: + """Change capacity by fixed steps when a CloudWatch alarm fires. + + Args: + steps (list[StepAdjustment]): The adjustments, by how far the metric is past the + threshold. + alarm (Alarm): The alarm this module creates for the policy. + adjustment_type (str): ``"ChangeInCapacity"`` (default), ``"ExactCapacity"`` or + ``"PercentChangeInCapacity"``. + metric_aggregation_type (str): ``"Average"`` (default), ``"Minimum"`` or ``"Maximum"``. + cooldown (int): Seconds after a scaling activity before the next one (default 300). + min_adjustment_magnitude (int): For ``"PercentChangeInCapacity"``, the smallest change. + name (str): Distinguishes this policy from the target's other step-scaling policies. + """ + + steps: List[StepAdjustment] + alarm: Alarm + adjustment_type: str = "ChangeInCapacity" + metric_aggregation_type: str = "Average" + cooldown: int = 300 + min_adjustment_magnitude: Optional[int] = None + name: Optional[str] = None + + +@dataclass +class ScheduledAction: + """Change the scalable target's bounds on a schedule. + + Args: + name (str): The action's name, unique on the target. + schedule (str): ``"at(yyyy-mm-ddThh:mm:ss)"``, ``"rate(value unit)"`` or + ``"cron(fields)"``. + min_capacity (int): The minimum from then on. + max_capacity (int): The maximum from then on. + timezone (str): The schedule's time zone, such as ``"America/New_York"`` (default UTC). + start_time (datetime): When a recurring schedule starts. + end_time (datetime): When a recurring schedule ends. + """ + + name: str + schedule: str + min_capacity: Optional[int] = None + max_capacity: Optional[int] = None + timezone: Optional[str] = None + start_time: Optional[datetime] = None + end_time: Optional[datetime] = None + + +@dataclass +class ScalingTarget: + """What autoscaling applies to: a production variant or an inference component.""" + + kind: str + endpoint_name: str + resource_id: str + name: str + variant_name: Optional[str] = None + inference_component_name: Optional[str] = None + asynchronous: bool = False + adapters: List[str] = field(default_factory=list) + managed_instance_scaling: Optional[Dict[str, Any]] = None + + @property + def scalable_dimension(self) -> str: + """The Application Auto Scaling dimension this target scales.""" + return DIMENSIONS[self.kind] + + @property + def metric_dimensions(self) -> Dict[str, str]: + """The CloudWatch dimensions of this target's own metrics.""" + if self.kind == INFERENCE_COMPONENT: + return {"InferenceComponentName": self.inference_component_name} + return {"EndpointName": self.endpoint_name, "VariantName": self.variant_name} + + def target_kwargs(self) -> Dict[str, str]: + """The keyword arguments that name this target in Application Auto Scaling calls.""" + return { + "ServiceNamespace": SERVICE_NAMESPACE, + "ResourceId": self.resource_id, + "ScalableDimension": self.scalable_dimension, + } + + def alarm_name(self, policy_name: str) -> str: + """The name of the alarm this module creates for a step-scaling policy.""" + return f"{policy_name}-{self.name}" + + +class _Clients: + """The SageMaker, Application Auto Scaling and CloudWatch clients of a session.""" + + def __init__(self, sagemaker_session: Optional[Session]): + session = sagemaker_session or Session() + region = session.boto_region_name + self.sagemaker = session.sagemaker_client + self.autoscaling = session.boto_session.client( + "application-autoscaling", region_name=region + ) + self.cloudwatch = session.boto_session.client("cloudwatch", region_name=region) + + +def enable_autoscaling( + *, + min_capacity: int, + max_capacity: int, + target_value: Optional[float] = None, + metric: Union[str, CustomMetric, Dict[str, Any], None] = None, + endpoint_name: Optional[str] = None, + variant_name: Optional[str] = None, + inference_component_name: Optional[str] = None, + policies: Optional[List[Union[TargetTrackingPolicy, StepScalingPolicy]]] = None, + scheduled_actions: Optional[List[ScheduledAction]] = None, + scale_in_cooldown: int = 300, + scale_out_cooldown: int = 300, + disable_scale_in: bool = False, + scale_to_zero: bool = False, + wait: bool = True, + sagemaker_session: Optional[Session] = None, +) -> Dict[str, Any]: + """Turn on, or change, autoscaling for an endpoint or inference component. + + Pass ``target_value`` (with ``metric`` and the cooldown arguments) for one target-tracking + policy, or ``policies`` for any mix of policies; ``scheduled_actions`` can go with either, or + alone. The policies and scheduled actions given replace the ones this module set before. + + Args: + min_capacity (int): Minimum instances, copies or provisioned concurrency; at least 1, + or 0 for an asynchronous endpoint or, with ``scale_to_zero``, an inference component. + max_capacity (int): Maximum instances, copies or provisioned concurrency. + target_value (float): For one target-tracking policy: the metric's target value. + metric: For one target-tracking policy: the metric (see :class:`TargetTrackingPolicy`). + endpoint_name (str): The endpoint, to scale its production variant. + variant_name (str): The variant, when the endpoint has more than one. + inference_component_name (str): The inference component, to scale its copies. On an + endpoint with LoRA adapters, the base component (the adapters run on its copies). + policies (list): :class:`TargetTrackingPolicy` and :class:`StepScalingPolicy` objects. + scheduled_actions (list[ScheduledAction]): Scheduled changes to the bounds. + scale_in_cooldown (int): For one target-tracking policy (default 300). + scale_out_cooldown (int): For one target-tracking policy (default 300). + disable_scale_in (bool): For one target-tracking policy (default False). + scale_to_zero (bool): Add the step-scaling policy and CloudWatch alarm that add capacity + when a request arrives at zero: on ``NoCapacityInvocationFailures`` for an inference + component (which needs ``min_capacity=0`` and managed instance scaling with + ``MinInstanceCount`` 0), on ``HasBacklogWithoutCapacity`` for an asynchronous + endpoint. A request to an inference component at zero fails while a copy starts, + which takes several minutes; an asynchronous request waits in the queue. + wait (bool): Wait until the change reads back (default True). + sagemaker_session (Session): The session to use; a default one if omitted. + + Returns: + dict: The resulting configuration, as :func:`describe_autoscaling` returns it. + + Raises: + ValueError: If the arguments or the endpoint cannot be autoscaled as asked. Nothing is + changed. + """ + if policies is None and target_value is not None: + policies = [ + TargetTrackingPolicy( + target_value=target_value, + metric=metric, + scale_in_cooldown=scale_in_cooldown, + scale_out_cooldown=scale_out_cooldown, + disable_scale_in=disable_scale_in, + ) + ] + elif policies is not None and (target_value is not None or metric is not None): + raise ValueError("Pass target_value and metric, or policies, not both.") + elif policies is None and metric is not None: + raise ValueError("metric needs a target_value (or pass policies).") + policies = list(policies or []) + scheduled_actions = list(scheduled_actions or []) + if not policies and not scheduled_actions and not scale_to_zero: + raise ValueError("Pass target_value, policies or scheduled_actions.") + + clients = _Clients(sagemaker_session) + target = _resolve_target( + clients, endpoint_name, variant_name, inference_component_name, for_apply=True + ) + _validate_capacity(target, min_capacity, max_capacity, scale_to_zero) + requests = [_policy_request(target, policy) for policy in policies] + if scale_to_zero: + requests.append(_policy_request(target, _scale_out_from_zero_policy(target))) + _check_unique([request["PolicyName"] for request in requests], "policy") + schedule_requests = [_schedule_request(action) for action in scheduled_actions] + _check_unique( + [request["ScheduledActionName"] for request in schedule_requests], "scheduled action" + ) + + current = _read(clients, target) + registered_before = current["scalable_target"] is not None + # With scale to zero on an inference component, keep a minimum of 1 until the alarm that + # scales out from 0 exists, so a failed alarm write cannot leave a component that scales in + # to 0 and never back out. + lower_last = ( + scale_to_zero + and target.kind == INFERENCE_COMPONENT + and not (registered_before and current["scalable_target"]["MinCapacity"] == 0) + ) + register = dict( + target.target_kwargs(), + MinCapacity=1 if lower_last else min_capacity, + MaxCapacity=max_capacity, + ) + if not registered_before: + register["Tags"] = {OWNER_TAG_KEY: OWNER_TAG_VALUE} + clients.autoscaling.register_scalable_target(**register) + + for request in requests: + alarm = request.pop("_alarm", None) + arn = clients.autoscaling.put_scaling_policy(**target.target_kwargs(), **request)[ + "PolicyARN" + ] + if alarm is not None: + clients.cloudwatch.put_metric_alarm(**alarm, AlarmActions=[arn]) + for request in schedule_requests: + clients.autoscaling.put_scheduled_action(**target.target_kwargs(), **request) + + wanted = {request["PolicyName"] for request in requests} + for name in sorted(_managed(_policy_names(current)) - wanted): + clients.autoscaling.delete_scaling_policy(**target.target_kwargs(), PolicyName=name) + _delete_alarm(clients, target.alarm_name(name)) + wanted_schedules = {request["ScheduledActionName"] for request in schedule_requests} + for name in sorted(_managed(_schedule_names(current)) - wanted_schedules): + clients.autoscaling.delete_scheduled_action( + **target.target_kwargs(), ScheduledActionName=name + ) + + if lower_last: + clients.autoscaling.register_scalable_target( + **target.target_kwargs(), MinCapacity=0, MaxCapacity=max_capacity + ) + + if wait: + return _wait_for( + clients, + target, + lambda state: state["scalable_target"] is not None + and _managed(_policy_names(state)) == wanted + and _managed(_schedule_names(state)) == wanted_schedules + and state["scalable_target"]["MinCapacity"] == min_capacity + and state["scalable_target"]["MaxCapacity"] == max_capacity, + ) + return _read(clients, target) + + +def disable_autoscaling( + *, + endpoint_name: Optional[str] = None, + variant_name: Optional[str] = None, + inference_component_name: Optional[str] = None, + wait: bool = True, + sagemaker_session: Optional[Session] = None, +) -> Dict[str, Any]: + """Turn off the autoscaling that :func:`enable_autoscaling` set up. + + Deletes this module's policies, their alarms and its scheduled actions, then deregisters + the scalable target when this module registered it and no other policy or scheduled action + is on it. Otherwise the target and everything else on it stay. The capacity stays where + scaling left it. + + Args: + endpoint_name (str): The endpoint whose production variant was scaled. + variant_name (str): The variant, when the endpoint has more than one. + inference_component_name (str): The inference component whose copies were scaled. + wait (bool): Wait until the change reads back (default True). + sagemaker_session (Session): The session to use; a default one if omitted. + + Returns: + dict: ``{"deregistered": bool, "deleted_policies": [...], + "deleted_scheduled_actions": [...], "remaining": {...}}``, where ``remaining`` is what + :func:`describe_autoscaling` returns afterwards. + """ + clients = _Clients(sagemaker_session) + target = _resolve_target( + clients, endpoint_name, variant_name, inference_component_name, for_apply=False + ) + current = _read(clients, target) + policies = sorted(_managed(_policy_names(current))) + schedules = sorted(_managed(_schedule_names(current))) + others = (_policy_names(current) - set(policies)) | (_schedule_names(current) - set(schedules)) + deregister = ( + current["scalable_target"] is not None + and _is_ours(clients, current["scalable_target"]) + and not others + ) + if deregister: + # Deregistering deletes the target's policies and scheduled actions too. + clients.autoscaling.deregister_scalable_target(**target.target_kwargs()) + else: + for name in policies: + clients.autoscaling.delete_scaling_policy(**target.target_kwargs(), PolicyName=name) + for name in schedules: + clients.autoscaling.delete_scheduled_action( + **target.target_kwargs(), ScheduledActionName=name + ) + if current["scalable_target"] is not None and not policies and not schedules: + logger.warning( + "%s has no policy or scheduled action created by enable_autoscaling; nothing was " + "deleted.", + target.resource_id, + ) + for name in policies: + _delete_alarm(clients, target.alarm_name(name)) + + if wait: + remaining = _wait_for( + clients, + target, + lambda state: ( + (state["scalable_target"] is None) + if deregister + else not (_managed(_policy_names(state)) or _managed(_schedule_names(state))) + ), + ) + else: + remaining = _read(clients, target) + return { + "deregistered": deregister, + "deleted_policies": policies, + "deleted_scheduled_actions": schedules, + "remaining": remaining, + } + + +def suspend_autoscaling( + *, + endpoint_name: Optional[str] = None, + variant_name: Optional[str] = None, + inference_component_name: Optional[str] = None, + scale_in: bool = True, + scale_out: bool = True, + scheduled: bool = True, + sagemaker_session: Optional[Session] = None, +) -> Dict[str, Any]: + """Pause scaling on a registered target, keeping its policies and scheduled actions. + + Args: + scale_in (bool): Pause scale-in by the scaling policies (default True). + scale_out (bool): Pause scale-out by the scaling policies (default True). + scheduled (bool): Pause the scheduled actions (default True). + + Returns: + dict: The resulting configuration, as :func:`describe_autoscaling` returns it. + """ + return _set_suspended( + endpoint_name, + variant_name, + inference_component_name, + { + "DynamicScalingInSuspended": scale_in, + "DynamicScalingOutSuspended": scale_out, + "ScheduledScalingSuspended": scheduled, + }, + sagemaker_session, + ) + + +def resume_autoscaling( + *, + endpoint_name: Optional[str] = None, + variant_name: Optional[str] = None, + inference_component_name: Optional[str] = None, + sagemaker_session: Optional[Session] = None, +) -> Dict[str, Any]: + """Resume scaling that :func:`suspend_autoscaling` paused. + + Returns: + dict: The resulting configuration, as :func:`describe_autoscaling` returns it. + """ + return _set_suspended( + endpoint_name, + variant_name, + inference_component_name, + { + "DynamicScalingInSuspended": False, + "DynamicScalingOutSuspended": False, + "ScheduledScalingSuspended": False, + }, + sagemaker_session, + ) + + +def describe_autoscaling( + *, + endpoint_name: Optional[str] = None, + variant_name: Optional[str] = None, + inference_component_name: Optional[str] = None, + sagemaker_session: Optional[Session] = None, +) -> Dict[str, Any]: + """The scalable target, scaling policies and scheduled actions of an endpoint or component. + + Returns: + dict: ``{"resource_id": str, "scalable_dimension": str, "scalable_target": dict or None, + "policies": [...], "scheduled_actions": [...]}``, with the Application Auto Scaling + responses' fields. The scalable target's ``SuspendedState`` says whether scaling is + paused. + """ + clients = _Clients(sagemaker_session) + target = _resolve_target( + clients, endpoint_name, variant_name, inference_component_name, for_apply=False + ) + return _read(clients, target) + + +def _set_suspended(endpoint_name, variant_name, inference_component_name, state, session): + clients = _Clients(session) + target = _resolve_target( + clients, endpoint_name, variant_name, inference_component_name, for_apply=False + ) + if _read(clients, target)["scalable_target"] is None: + raise ValueError(f"{target.resource_id} is not registered for autoscaling.") + clients.autoscaling.register_scalable_target(**target.target_kwargs(), SuspendedState=state) + return _wait_for( + clients, + target, + lambda current: current["scalable_target"] is not None + and all( + current["scalable_target"].get("SuspendedState", {}).get(key, False) == value + for key, value in state.items() + ), + ) + + +def _int(name, value, minimum): + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise ValueError(f"{name} must be an integer >= {minimum}, got {value!r}.") + + +def _validate_capacity(target, min_capacity, max_capacity, scale_to_zero): + _int("max_capacity", max_capacity, 1) + if scale_to_zero: + if target.kind == PROVISIONED_CONCURRENCY: + raise ValueError( + "A serverless endpoint's provisioned concurrency does not scale to zero." + ) + if target.kind == VARIANT and not target.asynchronous: + raise ValueError( + "scale_to_zero applies to an inference component or an asynchronous endpoint; a " + "real-time production variant keeps at least 1 instance." + ) + if min_capacity != 0: + raise ValueError("scale_to_zero needs min_capacity=0.") + if target.kind == INFERENCE_COMPONENT: + minimum = (target.managed_instance_scaling or {}).get("MinInstanceCount") + if minimum != 0: + raise ValueError( + f"Managed instance scaling on {target.endpoint_name} keeps at least " + f"{minimum} instance(s), so the endpoint cannot reach zero: it needs " + "MinInstanceCount 0." + ) + if target.adapters: + raise ValueError( + f"scale_to_zero is not supported for a base component with adapters " + f"{target.adapters}: a request names its adapter, so the scale-out alarm " + "would not see it." + ) + _int("min_capacity", min_capacity, 0 if (scale_to_zero or target.asynchronous) else 1) + if min_capacity > max_capacity: + raise ValueError( + f"min_capacity ({min_capacity}) must not exceed max_capacity ({max_capacity})." + ) + + +def _resolve_target(clients, endpoint_name, variant_name, inference_component_name, for_apply): + if not endpoint_name and not inference_component_name: + raise ValueError("Pass endpoint_name, or inference_component_name, to scale.") + sm = clients.sagemaker + if inference_component_name: + component = sm.describe_inference_component(InferenceComponentName=inference_component_name) + if endpoint_name and component["EndpointName"] != endpoint_name: + raise ValueError( + f"{inference_component_name} is on {component['EndpointName']}, " + f"not {endpoint_name}." + ) + base = component.get("Specification", {}).get("BaseInferenceComponentName") + if base: + raise ValueError( + f"{inference_component_name} is an adapter on {base}, whose copies it runs on: " + f"scale inference_component_name={base!r}." + ) + endpoint_name = component["EndpointName"] + variant_name = component["VariantName"] + endpoint = sm.describe_endpoint(EndpointName=endpoint_name) + if for_apply and endpoint["EndpointStatus"] != "InService": + raise ValueError(f"{endpoint_name} is {endpoint['EndpointStatus']}, not InService.") + config = sm.describe_endpoint_config(EndpointConfigName=endpoint["EndpointConfigName"]) + variants = {v["VariantName"]: v for v in config["ProductionVariants"]} + if variant_name is None: + if len(variants) != 1: + raise ValueError(f"{endpoint_name} has variants {sorted(variants)}: pass variant_name.") + variant_name = next(iter(variants)) + if variant_name not in variants: + raise ValueError(f"{endpoint_name} has no variant {variant_name!r}.") + variant = variants[variant_name] + managed = variant.get("ManagedInstanceScaling") or None + + if inference_component_name: + if for_apply and (managed or {}).get("Status") != "ENABLED": + raise ValueError( + f"{endpoint_name} has no managed instance scaling, so it cannot add instances " + "for new copies. Managed instance scaling is set in the endpoint configuration " + "(deploy(managed_instance_scaling=...))." + ) + target = ScalingTarget( + kind=INFERENCE_COMPONENT, + endpoint_name=endpoint_name, + resource_id=f"inference-component/{inference_component_name}", + name=inference_component_name, + variant_name=variant_name, + inference_component_name=inference_component_name, + managed_instance_scaling=managed, + ) + target.adapters = _adapters(clients, target) if for_apply else [] + return target + + serverless = variant.get("ServerlessConfig") + if serverless: + if not serverless.get("ProvisionedConcurrency"): + raise ValueError( + f"Variant {variant_name} of {endpoint_name} is serverless without provisioned " + "concurrency; SageMaker scales on-demand serverless capacity itself." + ) + kind = PROVISIONED_CONCURRENCY + else: + if not variant.get("ModelName"): + raise ValueError( + f"Variant {variant_name} of {endpoint_name} hosts inference components: pass " + "inference_component_name to scale a component's copies." + ) + kind = VARIANT + return ScalingTarget( + kind=kind, + endpoint_name=endpoint_name, + resource_id=f"endpoint/{endpoint_name}/variant/{variant_name}", + name=f"{endpoint_name}-{variant_name}", + variant_name=variant_name, + asynchronous=bool(config.get("AsyncInferenceConfig")), + ) + + +def _adapters(clients, target) -> List[str]: + names = [] + paginator = clients.sagemaker.get_paginator("list_inference_components") + for page in paginator.paginate(EndpointNameEquals=target.endpoint_name): + for summary in page["InferenceComponents"]: + name = summary["InferenceComponentName"] + if name == target.inference_component_name: + continue + spec = clients.sagemaker.describe_inference_component(InferenceComponentName=name).get( + "Specification", {} + ) + if spec.get("BaseInferenceComponentName") == target.inference_component_name: + names.append(name) + return names + + +def _metric_specification(target, metric) -> Dict[str, Any]: + """The metric part of a target-tracking configuration.""" + if metric is None: + metric = BACKLOG_PER_INSTANCE if target.asynchronous else next(iter(METRICS[target.kind])) + if isinstance(metric, dict): + return {"CustomizedMetricSpecification": metric} + if isinstance(metric, CustomMetric): + specification = { + "MetricName": metric.metric_name, + "Namespace": metric.namespace, + "Dimensions": metric._dimension_list(target), # pylint: disable=protected-access + "Statistic": metric.statistic, + } + if metric.unit: + specification["Unit"] = metric.unit + return {"CustomizedMetricSpecification": specification} + if metric == BACKLOG_PER_INSTANCE: + if not target.asynchronous: + raise ValueError("metric 'backlog-per-instance' applies to an asynchronous endpoint.") + return { + "CustomizedMetricSpecification": { + "MetricName": "ApproximateBacklogSizePerInstance", + "Namespace": "AWS/SageMaker", + "Dimensions": [{"Name": "EndpointName", "Value": target.endpoint_name}], + "Statistic": "Average", + } + } + predefined = METRICS[target.kind].get(metric) + if predefined is None and metric in METRICS[target.kind].values(): + predefined = metric + if predefined is None: + names = sorted(METRICS[target.kind]) + ( + [BACKLOG_PER_INSTANCE] if target.asynchronous else [] + ) + raise ValueError( + f"metric {metric!r} does not apply to a {target.kind}: use one of {names}, a full " + "predefined metric type, or a CustomMetric." + ) + if target.adapters and predefined == METRICS[INFERENCE_COMPONENT]["invocations"]: + raise ValueError( + f"{target.name} has adapters {target.adapters}: use metric 'concurrent-requests', " + "which counts the requests its adapters serve." + ) + return {"PredefinedMetricSpecification": {"PredefinedMetricType": predefined}} + + +def _policy_request(target, policy) -> Dict[str, Any]: + """A PutScalingPolicy request (without the target) and, for step scaling, its alarm.""" + name = getattr(policy, "name", None) + suffix = f"-{name}" if name else "" + if isinstance(policy, TargetTrackingPolicy): + if ( + isinstance(policy.target_value, bool) + or not isinstance(policy.target_value, (int, float)) + or policy.target_value <= 0 + ): + raise ValueError(f"target_value must be a number > 0, got {policy.target_value!r}.") + _int("scale_in_cooldown", policy.scale_in_cooldown, 0) + _int("scale_out_cooldown", policy.scale_out_cooldown, 0) + configuration = { + "TargetValue": float(policy.target_value), + "ScaleInCooldown": policy.scale_in_cooldown, + "ScaleOutCooldown": policy.scale_out_cooldown, + "DisableScaleIn": policy.disable_scale_in, + } + configuration.update(_metric_specification(target, policy.metric)) + return { + "PolicyName": f"{NAME_PREFIX}target-tracking{suffix}", + "PolicyType": "TargetTrackingScaling", + "TargetTrackingScalingPolicyConfiguration": configuration, + } + if isinstance(policy, StepScalingPolicy): + if not policy.steps: + raise ValueError("A StepScalingPolicy needs at least one step.") + _int("cooldown", policy.cooldown, 0) + steps = [] + for step in policy.steps: + adjustment = {"ScalingAdjustment": step.scaling_adjustment} + if step.lower_bound is not None: + adjustment["MetricIntervalLowerBound"] = step.lower_bound + if step.upper_bound is not None: + adjustment["MetricIntervalUpperBound"] = step.upper_bound + steps.append(adjustment) + configuration = { + "AdjustmentType": policy.adjustment_type, + "MetricAggregationType": policy.metric_aggregation_type, + "Cooldown": policy.cooldown, + "StepAdjustments": steps, + } + if policy.min_adjustment_magnitude is not None: + configuration["MinAdjustmentMagnitude"] = policy.min_adjustment_magnitude + name = f"{NAME_PREFIX}step-scaling{suffix}" + return { + "PolicyName": name, + "PolicyType": "StepScaling", + "StepScalingPolicyConfiguration": configuration, + "_alarm": _alarm_request(target, target.alarm_name(name), policy.alarm), + } + raise ValueError( + f"policies must be TargetTrackingPolicy or StepScalingPolicy objects, got " + f"{type(policy).__name__}." + ) + + +def _alarm_request(target, name, alarm: Alarm) -> Dict[str, Any]: + request = { + "AlarmName": name, + "AlarmDescription": f"Drives a scaling policy of {target.resource_id}.", + "Namespace": alarm.metric.namespace, + "MetricName": alarm.metric.metric_name, + "Dimensions": alarm.metric._dimension_list(target), # pylint: disable=protected-access + "Statistic": alarm.metric.statistic, + "Period": alarm.period, + "EvaluationPeriods": alarm.evaluation_periods, + "DatapointsToAlarm": alarm.datapoints_to_alarm or alarm.evaluation_periods, + "Threshold": alarm.threshold, + "ComparisonOperator": alarm.comparison_operator, + "TreatMissingData": alarm.treat_missing_data, + "Tags": [{"Key": OWNER_TAG_KEY, "Value": OWNER_TAG_VALUE}], + } + if alarm.metric.unit: + request["Unit"] = alarm.metric.unit + return request + + +def _scale_out_from_zero_policy(target) -> StepScalingPolicy: + """The step policy that adds capacity when a request arrives at zero.""" + if target.kind == INFERENCE_COMPONENT: + # Target tracking cannot scale out from 0 copies (there is no metric to track). + alarm = Alarm( + metric=CustomMetric("NoCapacityInvocationFailures", statistic="Sum"), + threshold=1, + treat_missing_data="notBreaching", + ) + return StepScalingPolicy( + steps=[StepAdjustment(scaling_adjustment=1, lower_bound=0)], + alarm=alarm, + metric_aggregation_type="Maximum", + cooldown=60, + name=_SCALE_OUT_FROM_ZERO, + ) + # An asynchronous endpoint otherwise waits until the backlog exceeds the tracking target. + alarm = Alarm( + metric=CustomMetric( + "HasBacklogWithoutCapacity", dimensions={"EndpointName": target.endpoint_name} + ), + threshold=1, + evaluation_periods=2, + ) + return StepScalingPolicy( + steps=[StepAdjustment(scaling_adjustment=1, lower_bound=0)], + alarm=alarm, + name=_SCALE_OUT_FROM_ZERO, + ) + + +def _schedule_request(action: ScheduledAction) -> Dict[str, Any]: + if not isinstance(action, ScheduledAction): + raise ValueError(f"scheduled_actions must be ScheduledAction objects, got {action!r}.") + if not action.name: + raise ValueError("A ScheduledAction needs a name.") + if not str(action.schedule).startswith(("at(", "rate(", "cron(")): + raise ValueError( + f"schedule must be at(...), rate(...) or cron(...), got {action.schedule!r}." + ) + bounds = {} + for key, value in (("MinCapacity", action.min_capacity), ("MaxCapacity", action.max_capacity)): + if value is not None: + _int(key, value, 0) + bounds[key] = value + if not bounds: + raise ValueError(f"ScheduledAction {action.name!r} needs min_capacity or max_capacity.") + request = { + "ScheduledActionName": f"{NAME_PREFIX}{action.name}", + "Schedule": action.schedule, + "ScalableTargetAction": bounds, + } + if action.timezone: + request["Timezone"] = action.timezone + if action.start_time: + request["StartTime"] = action.start_time + if action.end_time: + request["EndTime"] = action.end_time + return request + + +def _check_unique(names, what): + duplicates = sorted({name for name in names if names.count(name) > 1}) + if duplicates: + raise ValueError(f"Each {what} needs a distinct name; {duplicates} repeat.") + + +def _delete_alarm(clients, name): + # A step policy's alarm outlives the policy; delete it only when this module created it. + for alarm in clients.cloudwatch.describe_alarms(AlarmNames=[name])["MetricAlarms"]: + tags = clients.cloudwatch.list_tags_for_resource(ResourceARN=alarm["AlarmArn"])["Tags"] + if {"Key": OWNER_TAG_KEY, "Value": OWNER_TAG_VALUE} in tags: + clients.cloudwatch.delete_alarms(AlarmNames=[name]) + + +def _is_ours(clients, scalable_target) -> bool: + arn = scalable_target.get("ScalableTargetARN") + if not arn: + return False + tags = clients.autoscaling.list_tags_for_resource(ResourceARN=arn).get("Tags", {}) + return tags.get(OWNER_TAG_KEY) == OWNER_TAG_VALUE + + +def _all_pages(client, operation, key, **kwargs) -> List[Dict[str, Any]]: + """Every item an Application Auto Scaling describe call returns, across pages.""" + items = [] + for page in client.get_paginator(operation).paginate(**kwargs): + items.extend(page[key]) + return items + + +def _read(clients, target) -> Dict[str, Any]: + aas = clients.autoscaling + targets = _all_pages( + aas, + "describe_scalable_targets", + "ScalableTargets", + ServiceNamespace=SERVICE_NAMESPACE, + ResourceIds=[target.resource_id], + ScalableDimension=target.scalable_dimension, + ) + return { + "resource_id": target.resource_id, + "scalable_dimension": target.scalable_dimension, + "scalable_target": targets[0] if targets else None, + "policies": _all_pages( + aas, "describe_scaling_policies", "ScalingPolicies", **target.target_kwargs() + ), + "scheduled_actions": _all_pages( + aas, "describe_scheduled_actions", "ScheduledActions", **target.target_kwargs() + ), + } + + +def _policy_names(state) -> set: + return {p["PolicyName"] for p in state["policies"]} + + +def _schedule_names(state) -> set: + return {a["ScheduledActionName"] for a in state["scheduled_actions"]} + + +def _managed(names) -> set: + return {name for name in names if name.startswith(NAME_PREFIX)} + + +def _wait_for(clients, target, settled) -> Dict[str, Any]: + # Application Auto Scaling is eventually consistent: a write can take seconds to read back. + for attempt in range(_READ_BACK_ATTEMPTS): + state = _read(clients, target) + if settled(state): + return state + if attempt < _READ_BACK_ATTEMPTS - 1: + time.sleep(_READ_BACK_DELAY_SECONDS) + logger.warning( + "The change to %s was accepted but does not read back yet; check describe_autoscaling.", + target.resource_id, + ) + return state diff --git a/sagemaker-serve/src/sagemaker/serve/model_builder.py b/sagemaker-serve/src/sagemaker/serve/model_builder.py index 07e7c18268..359bf4ce10 100644 --- a/sagemaker-serve/src/sagemaker/serve/model_builder.py +++ b/sagemaker-serve/src/sagemaker/serve/model_builder.py @@ -50,6 +50,7 @@ InferenceComponentContainerSpecification, InferenceComponentRuntimeConfig, ProductionVariant, + ProductionVariantManagedInstanceScaling, ) from sagemaker.core.resources import ( ModelPackage, @@ -6443,6 +6444,44 @@ def deploy( raise ValueError("Deployment Options not supported") + @staticmethod + def _model_customization_managed_instance_scaling( + managed_instance_scaling: Dict[str, int], initial_instance_count: int + ) -> ProductionVariantManagedInstanceScaling: + """Build the managed instance scaling of a model customization endpoint configuration. + + Takes the same ``{"MinInstanceCount": ..., "MaxInstanceCount": ...}`` dict as + ``deploy(managed_instance_scaling=...)`` on the other deploy paths; ``MinInstanceCount`` + defaults to the initial instance count. + + Raises: + ValueError: If ``MaxInstanceCount`` is missing, or below ``MinInstanceCount`` or 1. + """ + min_count = managed_instance_scaling.get("MinInstanceCount", initial_instance_count) + max_count = managed_instance_scaling.get("MaxInstanceCount") + if ( + not isinstance(max_count, int) + or isinstance(max_count, bool) + or max_count < max(min_count, 1) + ): + raise ValueError( + "managed_instance_scaling needs a MaxInstanceCount of at least 1 and at least " + f"MinInstanceCount ({min_count}), got {max_count!r}." + ) + return ProductionVariantManagedInstanceScaling( + status="ENABLED", min_instance_count=min_count, max_instance_count=max_count + ) + + @staticmethod + def _warn_managed_instance_scaling_ignored(kwargs: Dict[str, Any], reason: str) -> None: + """Say that managed_instance_scaling does not apply to a deployment, instead of dropping it.""" + if kwargs.get("managed_instance_scaling"): + logger.warning( + "managed_instance_scaling applies to endpoints that host inference components; " + "it is ignored for %s.", + reason, + ) + def _deploy_model_customization( self, endpoint_name: str, @@ -6483,6 +6522,9 @@ def _deploy_model_customization( # image, escrow artifacts, and env. is_nova = self._is_nova_model() if is_nova and not is_ic_deploy: + self._warn_managed_instance_scaling_ignored( + kwargs, "a Nova model deployed on the endpoint's variant" + ) return self._deploy_nova_model( endpoint_name=endpoint_name, initial_instance_count=initial_instance_count, @@ -6499,6 +6541,9 @@ def _deploy_model_customization( from sagemaker.serve.utils.model_package_utils import is_restricted_model_package if not is_ic_deploy and is_restricted_model_package(model_package): + self._warn_managed_instance_scaling_ignored( + kwargs, "a restricted model package deployed on the endpoint's variant" + ) if not endpoint_name: endpoint_name = f"endpoint-{uuid.uuid4().hex[:8]}" EndpointConfig.create( @@ -6586,7 +6631,24 @@ def _deploy_model_customization( # Check if endpoint exists is_existing_endpoint = self._does_endpoint_exist(endpoint_name) + # Managed instance scaling lets SageMaker add and remove instances as the + # inference component copies change, as on the non-customization deploy path. + managed_instance_scaling = kwargs.get("managed_instance_scaling") + if managed_instance_scaling and is_existing_endpoint: + logger.warning( + "managed_instance_scaling applies only to a new endpoint's configuration; " + "endpoint '%s' already exists, so its instance scaling stays as it is.", + endpoint_name, + ) + if not is_existing_endpoint: + variant_kwargs = {} + if managed_instance_scaling: + variant_kwargs["managed_instance_scaling"] = ( + self._model_customization_managed_instance_scaling( + managed_instance_scaling, initial_instance_count or 1 + ) + ) EndpointConfig.create( endpoint_config_name=endpoint_name, production_variants=[ @@ -6594,6 +6656,7 @@ def _deploy_model_customization( variant_name=endpoint_name, instance_type=self.instance_type, initial_instance_count=initial_instance_count or 1, + **variant_kwargs, ) ], execution_role_arn=self.role_arn, diff --git a/sagemaker-serve/tests/integ/test_autoscaling_integration.py b/sagemaker-serve/tests/integ/test_autoscaling_integration.py new file mode 100644 index 0000000000..dd96da49df --- /dev/null +++ b/sagemaker-serve/tests/integ/test_autoscaling_integration.py @@ -0,0 +1,460 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +"""Integration tests for sagemaker.serve.autoscaling. + +Each test creates its own CPU endpoint from a small public JumpStart model (MobileNet v2), +exercises autoscaling on it, then deletes everything it created. The execution role is +``SAGEMAKER_INTEG_ROLE_ARN`` when set, else the caller's role. +""" + +from __future__ import absolute_import + +import json +import logging +import os +import tarfile +import tempfile +import uuid + +import boto3 +import pytest + +from sagemaker.core.helper.session_helper import Session, get_execution_role +from sagemaker.core.resources import Endpoint, EndpointConfig, InferenceComponent, Model +from sagemaker.core.shapes import ( + AsyncInferenceConfig, + AsyncInferenceOutputConfig, + ContainerDefinition, + InferenceComponentComputeResourceRequirements, + InferenceComponentRuntimeConfig, + InferenceComponentSpecification, + ModelDataSource, + ProductionVariant, + ProductionVariantManagedInstanceScaling, + S3ModelDataSource, +) +from sagemaker.serve.autoscaling import ( + Alarm, + CustomMetric, + ScheduledAction, + StepAdjustment, + StepScalingPolicy, + TargetTrackingPolicy, + describe_autoscaling, + disable_autoscaling, + enable_autoscaling, + resume_autoscaling, + suspend_autoscaling, +) + +logger = logging.getLogger(__name__) + +HUB_CONTENT_NAME = "pytorch-ic-mobilenet-v2" +INSTANCE_TYPE = "ml.m5.large" +TRACKING = "sagemaker-sdk-target-tracking" +FROM_ZERO = "sagemaker-sdk-step-scaling-scale-out-from-zero" + + +@pytest.fixture(scope="module") +def sagemaker_session(): + return Session() + + +@pytest.fixture(scope="module") +def role(sagemaker_session): + return os.environ.get("SAGEMAKER_INTEG_ROLE_ARN") or get_execution_role( + sagemaker_session=sagemaker_session + ) + + +@pytest.fixture(scope="module") +def container(sagemaker_session): + """The public hub's hosting image, artifacts and environment for the model.""" + document = json.loads( + sagemaker_session.sagemaker_client.describe_hub_content( + HubName="SageMakerPublicHub", HubContentType="Model", HubContentName=HUB_CONTENT_NAME + )["HubContentDocument"] + ) + environment = { + variable["Name"]: str(variable["Default"]) + for variable in document.get("InferenceEnvironmentVariables", []) + if variable.get("Default") is not None + } + return ContainerDefinition( + image=document["HostingEcrUri"], + model_data_source=ModelDataSource( + s3_data_source=S3ModelDataSource( + s3_uri=document["HostingArtifactUri"], + s3_data_type="S3Prefix", + compression_type="None", + ) + ), + environment=environment, + ) + + +class _Resources: + """Creates a test endpoint's resources and deletes them in reverse order.""" + + def __init__(self, sagemaker_session, role, container, prefix): + self.session = sagemaker_session + self.boto = sagemaker_session.boto_session + self.role = role + self.container = container + self.name = f"{prefix}-{uuid.uuid4().hex[:8]}" + self.created = [] + + def endpoint(self, variant, **config_kwargs): + self.created.append( + Model.create( + model_name=self.name, + primary_container=self.container, + execution_role_arn=self.role, + session=self.boto, + ) + ) + self.created.append( + EndpointConfig.create( + endpoint_config_name=self.name, + production_variants=[variant], + session=self.boto, + **config_kwargs, + ) + ) + endpoint = Endpoint.create( + endpoint_name=self.name, endpoint_config_name=self.name, session=self.boto + ) + self.created.append(endpoint) + endpoint.wait_for_status("InService") + return endpoint + + def component(self): + component = InferenceComponent.create( + inference_component_name=f"{self.name}-ic", + endpoint_name=self.name, + variant_name="AllTraffic", + specification=InferenceComponentSpecification( + model_name=self.name, + compute_resource_requirements=InferenceComponentComputeResourceRequirements( + number_of_cpu_cores_required=1, min_memory_required_in_mb=1024 + ), + ), + runtime_config=InferenceComponentRuntimeConfig(copy_count=1), + session=self.boto, + ) + self.created.append(component) + component.wait_for_status("InService") + return component + + def cleanup(self, **scaled): + try: + disable_autoscaling(sagemaker_session=self.session, wait=False, **scaled) + except Exception as error: # noqa: BLE001 - best-effort cleanup + logger.warning("Could not turn off autoscaling on %s: %s", scaled, error) + for resource in reversed(self.created): + try: + resource.delete() + if isinstance(resource, (InferenceComponent, Endpoint)): + resource.wait_for_delete() + except Exception as error: # noqa: BLE001 - best-effort cleanup + logger.warning("Could not delete %s: %s", resource, error) + + +def _packed_artifact(sagemaker_session, container, key): + """Pack the hub's uncompressed artifact into model.tar.gz, which a serverless endpoint needs.""" + s3 = sagemaker_session.boto_session.client("s3") + source = container.model_data_source.s3_data_source.s3_uri + bucket, prefix = source[len("s3://") :].split("/", 1) + with tempfile.TemporaryDirectory() as tmp: + archive = os.path.join(tmp, "model.tar.gz") + with tarfile.open(archive, "w:gz") as tar: + for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix): + for item in page.get("Contents", []): + relative = item["Key"][len(prefix) :] + if not relative: + continue + local = os.path.join(tmp, "files", relative) + os.makedirs(os.path.dirname(local), exist_ok=True) + s3.download_file(bucket, item["Key"], local) + tar.add(local, arcname=relative) + target_bucket = sagemaker_session.default_bucket() + s3.upload_file(archive, target_bucket, key) + return f"s3://{target_bucket}/{key}" + + +def _alarm_count(sagemaker_session, name): + cloudwatch = boto3.client("cloudwatch", region_name=sagemaker_session.boto_region_name) + return len(cloudwatch.describe_alarms(AlarmNames=[name])["MetricAlarms"]) + + +def _policy_names(state): + return {policy["PolicyName"] for policy in state["policies"]} + + +def _realtime_variant(name, **kwargs): + return ProductionVariant( + variant_name="AllTraffic", + model_name=name, + instance_type=INSTANCE_TYPE, + initial_instance_count=1, + **kwargs, + ) + + +@pytest.mark.slow_test +def test_variant_policies_schedules_and_suspension(sagemaker_session, role, container): + resources = _Resources(sagemaker_session, role, container, "autoscale-variant") + name = resources.name + try: + resources.endpoint(_realtime_variant(name)) + cpu = CustomMetric("CPUUtilization", namespace="/aws/sagemaker/Endpoints") + state = enable_autoscaling( + endpoint_name=name, + min_capacity=1, + max_capacity=3, + policies=[ + TargetTrackingPolicy(target_value=5), + TargetTrackingPolicy(target_value=70, metric=cpu, name="cpu"), + StepScalingPolicy( + steps=[StepAdjustment(scaling_adjustment=1, lower_bound=0)], + alarm=Alarm(metric=cpu, threshold=90, evaluation_periods=2), + name="cpu-burst", + ), + ], + scheduled_actions=[ + ScheduledAction( + name="night", + schedule="cron(0 2 * * ? *)", + min_capacity=1, + max_capacity=2, + timezone="America/Los_Angeles", + ) + ], + sagemaker_session=sagemaker_session, + ) + assert state["resource_id"] == f"endpoint/{name}/variant/AllTraffic" + assert ( + state["scalable_target"]["MinCapacity"], + state["scalable_target"]["MaxCapacity"], + ) == ( + 1, + 3, + ) + assert _policy_names(state) == { + TRACKING, + f"{TRACKING}-cpu", + "sagemaker-sdk-step-scaling-cpu-burst", + } + by_name = {policy["PolicyName"]: policy for policy in state["policies"]} + custom = by_name[f"{TRACKING}-cpu"]["TargetTrackingScalingPolicyConfiguration"] + assert custom["CustomizedMetricSpecification"]["MetricName"] == "CPUUtilization" + step_alarm = f"sagemaker-sdk-step-scaling-cpu-burst-{name}-AllTraffic" + assert _alarm_count(sagemaker_session, step_alarm) == 1 + (schedule,) = state["scheduled_actions"] + assert (schedule["ScheduledActionName"], schedule["Timezone"]) == ( + "sagemaker-sdk-night", + "America/Los_Angeles", + ) + + state = suspend_autoscaling(endpoint_name=name, sagemaker_session=sagemaker_session) + assert set(state["scalable_target"]["SuspendedState"].values()) == {True} + state = resume_autoscaling(endpoint_name=name, sagemaker_session=sagemaker_session) + assert set(state["scalable_target"]["SuspendedState"].values()) == {False} + + # Declarative: a policy and schedule no longer given are removed, with the step alarm. + state = enable_autoscaling( + endpoint_name=name, + min_capacity=1, + max_capacity=2, + target_value=100, + metric="invocations", + sagemaker_session=sagemaker_session, + ) + assert _policy_names(state) == {TRACKING} + assert state["scheduled_actions"] == [] + assert _alarm_count(sagemaker_session, step_alarm) == 0 + (policy,) = state["policies"] + assert policy["TargetTrackingScalingPolicyConfiguration"]["PredefinedMetricSpecification"][ + "PredefinedMetricType" + ] == ("SageMakerVariantInvocationsPerInstance") + + result = disable_autoscaling(endpoint_name=name, sagemaker_session=sagemaker_session) + assert result["deregistered"] is True + assert ( + describe_autoscaling(endpoint_name=name, sagemaker_session=sagemaker_session)[ + "scalable_target" + ] + is None + ) + finally: + resources.cleanup(endpoint_name=name) + + +@pytest.mark.slow_test +def test_inference_component_scale_to_zero_on_change_off(sagemaker_session, role, container): + resources = _Resources(sagemaker_session, role, container, "autoscale-ic") + name = resources.name + component_name = f"{name}-ic" + try: + # MinInstanceCount 0 goes through sagemaker-core shape serialization. + resources.endpoint( + ProductionVariant( + variant_name="AllTraffic", + instance_type=INSTANCE_TYPE, + initial_instance_count=1, + managed_instance_scaling=ProductionVariantManagedInstanceScaling( + status="ENABLED", min_instance_count=0, max_instance_count=2 + ), + ), + execution_role_arn=role, + ) + scaling = sagemaker_session.sagemaker_client.describe_endpoint_config( + EndpointConfigName=name + )["ProductionVariants"][0]["ManagedInstanceScaling"] + assert scaling == {"Status": "ENABLED", "MinInstanceCount": 0, "MaxInstanceCount": 2} + resources.component() + + state = enable_autoscaling( + inference_component_name=component_name, + min_capacity=0, + max_capacity=2, + target_value=4, + scale_to_zero=True, + sagemaker_session=sagemaker_session, + ) + assert state["scalable_dimension"] == "sagemaker:inference-component:DesiredCopyCount" + assert state["scalable_target"]["MinCapacity"] == 0 + assert _policy_names(state) == {TRACKING, FROM_ZERO} + alarm = f"{FROM_ZERO}-{component_name}" + assert _alarm_count(sagemaker_session, alarm) == 1 + + # Moving the minimum back to 1 removes the scale-out-from-zero policy and its alarm. + state = enable_autoscaling( + inference_component_name=component_name, + min_capacity=1, + max_capacity=2, + target_value=4, + sagemaker_session=sagemaker_session, + ) + assert state["scalable_target"]["MinCapacity"] == 1 + assert _policy_names(state) == {TRACKING} + assert _alarm_count(sagemaker_session, alarm) == 0 + + result = disable_autoscaling( + inference_component_name=component_name, sagemaker_session=sagemaker_session + ) + assert result["deregistered"] is True + assert result["remaining"]["scalable_target"] is None + finally: + resources.cleanup(inference_component_name=component_name) + + +@pytest.mark.slow_test +def test_asynchronous_endpoint_scales_to_zero_on_backlog(sagemaker_session, role, container): + resources = _Resources(sagemaker_session, role, container, "autoscale-async") + name = resources.name + output = f"s3://{sagemaker_session.default_bucket()}/autoscaling-integ/{name}/" + try: + resources.endpoint( + _realtime_variant(name), + async_inference_config=AsyncInferenceConfig( + output_config=AsyncInferenceOutputConfig(s3_output_path=output) + ), + ) + state = enable_autoscaling( + endpoint_name=name, + min_capacity=0, + max_capacity=2, + target_value=5, + scale_to_zero=True, + sagemaker_session=sagemaker_session, + ) + assert state["scalable_target"]["MinCapacity"] == 0 + assert _policy_names(state) == {TRACKING, FROM_ZERO} + by_name = {policy["PolicyName"]: policy for policy in state["policies"]} + tracking = by_name[TRACKING]["TargetTrackingScalingPolicyConfiguration"] + assert tracking["CustomizedMetricSpecification"]["MetricName"] == ( + "ApproximateBacklogSizePerInstance" + ) + alarm = f"{FROM_ZERO}-{name}-AllTraffic" + assert _alarm_count(sagemaker_session, alarm) == 1 + + result = disable_autoscaling(endpoint_name=name, sagemaker_session=sagemaker_session) + assert result["deregistered"] is True + assert _alarm_count(sagemaker_session, alarm) == 0 + finally: + resources.cleanup(endpoint_name=name) + + +@pytest.mark.slow_test +def test_serverless_provisioned_concurrency(sagemaker_session, role, container): + resources = _Resources(sagemaker_session, role, container, "autoscale-serverless") + name = resources.name + client = sagemaker_session.sagemaker_client + key = f"autoscaling-integ/{name}/model.tar.gz" + try: + artifact = _packed_artifact(sagemaker_session, container, key) + # Created with the client: a serverless endpoint needs a model.tar.gz (ModelDataUrl), and + # sagemaker-core serializes memory_size_in_mb as MemorySizeInMb. + client.create_model( + ModelName=name, + ExecutionRoleArn=role, + PrimaryContainer={ + "Image": container.image, + "ModelDataUrl": artifact, + "Environment": container.environment, + }, + ) + resources.created.append(Model.get(model_name=name, session=resources.boto)) + client.create_endpoint_config( + EndpointConfigName=name, + ProductionVariants=[ + { + "VariantName": "AllTraffic", + "ModelName": name, + "ServerlessConfig": { + "MemorySizeInMB": 2048, + "MaxConcurrency": 4, + "ProvisionedConcurrency": 1, + }, + } + ], + ) + resources.created.append( + EndpointConfig.get(endpoint_config_name=name, session=resources.boto) + ) + endpoint = Endpoint.create( + endpoint_name=name, endpoint_config_name=name, session=resources.boto + ) + resources.created.append(endpoint) + endpoint.wait_for_status("InService") + state = enable_autoscaling( + endpoint_name=name, + min_capacity=1, + max_capacity=2, + target_value=0.5, + sagemaker_session=sagemaker_session, + ) + assert state["scalable_dimension"] == "sagemaker:variant:DesiredProvisionedConcurrency" + (policy,) = state["policies"] + assert policy["TargetTrackingScalingPolicyConfiguration"]["PredefinedMetricSpecification"][ + "PredefinedMetricType" + ] == ("SageMakerVariantProvisionedConcurrencyUtilization") + + result = disable_autoscaling(endpoint_name=name, sagemaker_session=sagemaker_session) + assert result["deregistered"] is True + finally: + resources.cleanup(endpoint_name=name) + sagemaker_session.boto_session.client("s3").delete_object( + Bucket=sagemaker_session.default_bucket(), Key=key + ) diff --git a/sagemaker-serve/tests/integ/test_model_customization_deployment.py b/sagemaker-serve/tests/integ/test_model_customization_deployment.py index cb6ae6ece7..fcbeb44194 100644 --- a/sagemaker-serve/tests/integ/test_model_customization_deployment.py +++ b/sagemaker-serve/tests/integ/test_model_customization_deployment.py @@ -140,6 +140,7 @@ def test_deploy_from_training_job(self, training_job_name, sagemaker_session): endpoint = first_builder.deploy( endpoint_name=endpoint_name, inference_component_name=(adapter_ic_name if peft_type == "LORA" else None), + managed_instance_scaling={"MinInstanceCount": 1, "MaxInstanceCount": 2}, ) except (FailedStatusError, ClientError) as error: message = str(error) @@ -153,6 +154,17 @@ def test_deploy_from_training_job(self, training_job_name, sagemaker_session): assert model.model_name == model_name assert endpoint.endpoint_name == endpoint_name assert endpoint.endpoint_status == "InService" + # The model customization path sets managed instance scaling on the new endpoint + # configuration, so its inference components can add instances. + (variant,) = EndpointConfig.get( + endpoint_config_name=endpoint.endpoint_config_name, region=AWS_REGION + ).production_variants + scaling = variant.managed_instance_scaling + assert (scaling.status, scaling.min_instance_count, scaling.max_instance_count) == ( + "ENABLED", + 1, + 2, + ) sm_client = boto3.client("sagemaker", region_name=AWS_REGION) model_tags = sm_client.list_tags(ResourceArn=model.model_arn).get("Tags", []) diff --git a/sagemaker-serve/tests/unit/test_autoscaling.py b/sagemaker-serve/tests/unit/test_autoscaling.py new file mode 100644 index 0000000000..eda0075f58 --- /dev/null +++ b/sagemaker-serve/tests/unit/test_autoscaling.py @@ -0,0 +1,1275 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +"""Unit tests for sagemaker.serve.autoscaling.""" + +from __future__ import absolute_import + +from datetime import datetime +from unittest.mock import Mock, patch + +import pytest + +from sagemaker.serve import autoscaling +from sagemaker.serve.autoscaling import ( + OWNER_TAG_KEY, + OWNER_TAG_VALUE, + Alarm, + CustomMetric, + ScheduledAction, + StepAdjustment, + StepScalingPolicy, + TargetTrackingPolicy, + describe_autoscaling, + disable_autoscaling, + enable_autoscaling, + resume_autoscaling, + suspend_autoscaling, +) + +ENDPOINT = "my-endpoint" +VARIANT_ID = f"endpoint/{ENDPOINT}/variant/AllTraffic" +IC = "my-ic" +IC_ID = f"inference-component/{IC}" +TRACKING = "sagemaker-sdk-target-tracking" +FROM_ZERO = "sagemaker-sdk-step-scaling-scale-out-from-zero" +IC_FROM_ZERO_ALARM = f"{FROM_ZERO}-{IC}" +OWNER_TAGS = [{"Key": OWNER_TAG_KEY, "Value": OWNER_TAG_VALUE}] +WRITES = { + "register_scalable_target", + "deregister_scalable_target", + "put_scaling_policy", + "delete_scaling_policy", + "put_scheduled_action", + "delete_scheduled_action", + "put_metric_alarm", + "delete_alarms", +} + + +class FakeAWS: + """SageMaker, Application Auto Scaling and CloudWatch over one endpoint's state.""" + + def __init__( + self, + *, + status="InService", + variants=("AllTraffic",), + model_name="my-model", + managed=None, + serverless=None, + async_config=None, + components=None, + registered=None, + ours=True, + policies=(), + scheduled_actions=(), + alarms=None, + page_size=None, + ): + self.calls = [] + self.page_size = page_size + self.status = status + self.variants = variants + self.model_name = model_name + self.managed = managed + self.serverless = serverless + self.async_config = async_config + self.components = components or {} # {name: {"base": ..., "endpoint": ...}} + self.target = None + self.tags = {} + if registered is not None: + self.target = {"MinCapacity": registered[0], "MaxCapacity": registered[1]} + self.tags = {OWNER_TAG_KEY: OWNER_TAG_VALUE} if ours else {} + self.policies = { + name: {"PolicyName": name, "PolicyType": "TargetTrackingScaling"} for name in policies + } + self.scheduled = {n: {"ScheduledActionName": n} for n in scheduled_actions} + # {name: (alarm, tags)} + self.alarms = alarms or {} + self.sagemaker = Mock(name="sagemaker") + self.autoscaling = Mock(name="application-autoscaling") + self.cloudwatch = Mock(name="cloudwatch") + self._wire() + + def _record(self, client, name, func): + def call(*args, **kwargs): + self.calls.append((name, kwargs)) + return func(**kwargs) + + setattr(client, name, Mock(side_effect=call)) + + def _wire(self): + sm, aas, cw = self.sagemaker, self.autoscaling, self.cloudwatch + self._record(sm, "describe_endpoint", self._describe_endpoint) + self._record(sm, "describe_endpoint_config", self._describe_endpoint_config) + self._record(sm, "describe_inference_component", self._describe_component) + paginator = Mock() + paginator.paginate.side_effect = lambda EndpointNameEquals: [ + { + "InferenceComponents": [ + {"InferenceComponentName": n} + for n, c in self.components.items() + if c.get("endpoint", ENDPOINT) == EndpointNameEquals + ] + } + ] + sm.get_paginator.return_value = paginator + for name in ( + "describe_scalable_targets", + "describe_scaling_policies", + "describe_scheduled_actions", + "list_tags_for_resource", + "register_scalable_target", + "deregister_scalable_target", + "put_scaling_policy", + "delete_scaling_policy", + "put_scheduled_action", + "delete_scheduled_action", + ): + self._record(aas, name, getattr(self, "_aas_" + name)) + aas.get_paginator.side_effect = self._aas_paginator + for name in ( + "describe_alarms", + "put_metric_alarm", + "delete_alarms", + "list_tags_for_resource", + ): + self._record(cw, name, getattr(self, "_cw_" + name)) + + # SageMaker + def _describe_endpoint(self, EndpointName): + return { + "EndpointName": EndpointName, + "EndpointStatus": self.status, + "EndpointConfigName": f"{EndpointName}-config", + } + + def _describe_endpoint_config(self, EndpointConfigName): + variants = [] + for name in self.variants: + variant = {"VariantName": name} + if self.model_name: + variant["ModelName"] = self.model_name + if self.managed: + variant["ManagedInstanceScaling"] = self.managed + if self.serverless: + variant["ServerlessConfig"] = self.serverless + variants.append(variant) + config = {"ProductionVariants": variants} + if self.async_config: + config["AsyncInferenceConfig"] = self.async_config + return config + + def _describe_component(self, InferenceComponentName): + component = self.components[InferenceComponentName] + spec = {"BaseInferenceComponentName": component["base"]} if component.get("base") else {} + return { + "InferenceComponentName": InferenceComponentName, + "EndpointName": component.get("endpoint", ENDPOINT), + "VariantName": "AllTraffic", + "Specification": spec, + } + + # Application Auto Scaling + def _aas_paginator(self, operation): + # Pages over the recorded describe call, so a test that replaces it still takes effect. + key = { + "describe_scalable_targets": "ScalableTargets", + "describe_scaling_policies": "ScalingPolicies", + "describe_scheduled_actions": "ScheduledActions", + }[operation] + + def paginate(**kwargs): + items = getattr(self.autoscaling, operation)(**kwargs)[key] + size = self.page_size or max(len(items), 1) + return [{key: items[i : i + size]} for i in range(0, max(len(items), 1), size)] + + return Mock(paginate=Mock(side_effect=paginate)) + + def _aas_describe_scalable_targets(self, **kwargs): + if not self.target: + return {"ScalableTargets": []} + return {"ScalableTargets": [dict(self.target, ScalableTargetARN="arn:target")]} + + def _aas_describe_scaling_policies(self, **kwargs): + return {"ScalingPolicies": [dict(p) for p in self.policies.values()]} + + def _aas_describe_scheduled_actions(self, **kwargs): + return {"ScheduledActions": [dict(a) for a in self.scheduled.values()]} + + def _aas_list_tags_for_resource(self, ResourceARN): + return {"Tags": dict(self.tags)} + + def _aas_register_scalable_target(self, **kwargs): + if not self.target: + self.tags = dict(kwargs.get("Tags", {})) + self.target = {} + for key in ("MinCapacity", "MaxCapacity", "SuspendedState"): + if key in kwargs: + self.target[key] = kwargs[key] + + def _aas_deregister_scalable_target(self, **kwargs): + self.target, self.tags, self.policies, self.scheduled = None, {}, {}, {} + + def _aas_put_scaling_policy(self, **kwargs): + arn = f"arn:policy/{kwargs['PolicyName']}" + self.policies[kwargs["PolicyName"]] = { + "PolicyName": kwargs["PolicyName"], + "PolicyType": kwargs["PolicyType"], + "PolicyARN": arn, + } + return {"PolicyARN": arn} + + def _aas_delete_scaling_policy(self, **kwargs): + self.policies.pop(kwargs["PolicyName"], None) + + def _aas_put_scheduled_action(self, **kwargs): + self.scheduled[kwargs["ScheduledActionName"]] = { + "ScheduledActionName": kwargs["ScheduledActionName"], + "Schedule": kwargs["Schedule"], + } + + def _aas_delete_scheduled_action(self, **kwargs): + self.scheduled.pop(kwargs["ScheduledActionName"], None) + + # CloudWatch + def _cw_describe_alarms(self, AlarmNames): + return { + "MetricAlarms": [ + {"AlarmName": n, "AlarmArn": f"arn:alarm/{n}"} + for n in AlarmNames + if n in self.alarms + ] + } + + def _cw_list_tags_for_resource(self, ResourceARN): + return {"Tags": list(self.alarms[ResourceARN.split("/", 1)[1]][1])} + + def _cw_put_metric_alarm(self, **kwargs): + self.alarms[kwargs["AlarmName"]] = (kwargs, kwargs.get("Tags", [])) + + def _cw_delete_alarms(self, AlarmNames): + for name in AlarmNames: + self.alarms.pop(name, None) + + def called(self, name): + return [kwargs for call, kwargs in self.calls if call == name] + + def writes(self): + return [call for call, _ in self.calls if call in WRITES] + + +def _ic_aws(**kwargs): + kwargs.setdefault("model_name", None) + kwargs.setdefault( + "managed", {"Status": "ENABLED", "MinInstanceCount": 1, "MaxInstanceCount": 4} + ) + kwargs.setdefault("components", {IC: {}}) + return FakeAWS(**kwargs) + + +def _zero_ic_aws(**kwargs): + kwargs.setdefault( + "managed", {"Status": "ENABLED", "MinInstanceCount": 0, "MaxInstanceCount": 2} + ) + return _ic_aws(**kwargs) + + +@pytest.fixture +def run(): + def _run(aws, func, **kwargs): + with patch.object(autoscaling, "_Clients", return_value=aws), patch.object( + autoscaling.time, "sleep" + ) as sleep: + result = func(**kwargs) + return result, sleep + + return _run + + +def _policy(aws, name): + return next(p for p in aws.called("put_scaling_policy") if p["PolicyName"] == name) + + +class TestTargetTracking: + def test_registers_the_variant_and_puts_a_target_tracking_policy(self, run): + aws = FakeAWS() + result, _ = run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + target_value=8, + ) + (register,) = aws.called("register_scalable_target") + assert register == { + "ServiceNamespace": "sagemaker", + "ResourceId": VARIANT_ID, + "ScalableDimension": "sagemaker:variant:DesiredInstanceCount", + "MinCapacity": 1, + "MaxCapacity": 4, + "Tags": {OWNER_TAG_KEY: OWNER_TAG_VALUE}, + } + (policy,) = aws.called("put_scaling_policy") + assert policy["PolicyName"] == TRACKING + assert policy["PolicyType"] == "TargetTrackingScaling" + assert policy["TargetTrackingScalingPolicyConfiguration"] == { + "TargetValue": 8.0, + "PredefinedMetricSpecification": { + "PredefinedMetricType": "SageMakerVariantConcurrentRequestsPerModelHighResolution" + }, + "ScaleInCooldown": 300, + "ScaleOutCooldown": 300, + "DisableScaleIn": False, + } + assert result["scalable_target"]["MaxCapacity"] == 4 + assert aws.called("put_metric_alarm") == [] + + def test_a_change_does_not_retag_an_existing_target(self, run): + aws = FakeAWS(registered=(1, 2), ours=False, policies=(TRACKING,)) + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=2, + max_capacity=6, + target_value=5, + metric="invocations", + scale_in_cooldown=60, + scale_out_cooldown=30, + disable_scale_in=True, + ) + (register,) = aws.called("register_scalable_target") + assert "Tags" not in register + config = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert config["PredefinedMetricSpecification"] == { + "PredefinedMetricType": "SageMakerVariantInvocationsPerInstance" + } + assert ( + config["ScaleInCooldown"], + config["ScaleOutCooldown"], + config["DisableScaleIn"], + ) == ( + 60, + 30, + True, + ) + + def test_a_full_predefined_metric_type_is_accepted(self, run): + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=70, + metric="SageMakerVariantInvocationsPerInstance", + ) + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["PredefinedMetricSpecification"]["PredefinedMetricType"] == ( + "SageMakerVariantInvocationsPerInstance" + ) + + def test_a_custom_metric_defaults_to_the_targets_dimensions(self, run): + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=50, + metric=CustomMetric( + "CPUUtilization", namespace="/aws/sagemaker/Endpoints", unit="Percent" + ), + ) + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["CustomizedMetricSpecification"] == { + "MetricName": "CPUUtilization", + "Namespace": "/aws/sagemaker/Endpoints", + "Dimensions": [ + {"Name": "EndpointName", "Value": ENDPOINT}, + {"Name": "VariantName", "Value": "AllTraffic"}, + ], + "Statistic": "Average", + "Unit": "Percent", + } + assert "PredefinedMetricSpecification" not in spec + + def test_a_metric_math_dict_is_passed_through(self, run): + math = { + "Metrics": [ + { + "Id": "m1", + "MetricStat": { + "Metric": {"MetricName": "Invocations", "Namespace": "AWS/SageMaker"}, + "Stat": "Sum", + }, + "ReturnData": False, + }, + {"Id": "e1", "Expression": "m1 / 60", "ReturnData": True}, + ] + } + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=10, + metric=math, + ) + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["CustomizedMetricSpecification"] is math + + def test_several_target_tracking_policies_need_distinct_names(self, run): + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + policies=[ + TargetTrackingPolicy(target_value=4), + TargetTrackingPolicy( + target_value=70, + metric=CustomMetric("GPUUtilization", namespace="/aws/sagemaker/Endpoints"), + name="gpu", + ), + ], + ) + assert [p["PolicyName"] for p in aws.called("put_scaling_policy")] == [ + TRACKING, + f"{TRACKING}-gpu", + ] + aws = FakeAWS() + with pytest.raises(ValueError, match="distinct name"): + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + policies=[ + TargetTrackingPolicy(target_value=4), + TargetTrackingPolicy(target_value=5), + ], + ) + assert aws.writes() == [] + + def test_names_the_variant_when_the_endpoint_has_several(self, run): + aws = FakeAWS(variants=("A", "B")) + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + variant_name="B", + min_capacity=1, + max_capacity=2, + target_value=4, + ) + assert aws.called("register_scalable_target")[0]["ResourceId"] == ( + f"endpoint/{ENDPOINT}/variant/B" + ) + + def test_wait_false_returns_without_retrying(self, run): + aws = FakeAWS() + _, sleep = run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=4, + wait=False, + ) + assert sleep.call_count == 0 + + +class TestStepScaling: + def test_a_step_policy_gets_its_own_tagged_alarm(self, run): + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=6, + policies=[ + StepScalingPolicy( + steps=[ + StepAdjustment(scaling_adjustment=1, lower_bound=0, upper_bound=20), + StepAdjustment(scaling_adjustment=3, lower_bound=20), + ], + alarm=Alarm( + metric=CustomMetric("CPUUtilization", namespace="/aws/sagemaker/Endpoints"), + threshold=70, + evaluation_periods=3, + datapoints_to_alarm=2, + ), + adjustment_type="ChangeInCapacity", + cooldown=120, + name="cpu", + ) + ], + ) + (policy,) = aws.called("put_scaling_policy") + assert policy["PolicyName"] == "sagemaker-sdk-step-scaling-cpu" + assert policy["StepScalingPolicyConfiguration"] == { + "AdjustmentType": "ChangeInCapacity", + "MetricAggregationType": "Average", + "Cooldown": 120, + "StepAdjustments": [ + { + "ScalingAdjustment": 1, + "MetricIntervalLowerBound": 0, + "MetricIntervalUpperBound": 20, + }, + {"ScalingAdjustment": 3, "MetricIntervalLowerBound": 20}, + ], + } + (alarm,) = aws.called("put_metric_alarm") + assert alarm["AlarmName"] == f"sagemaker-sdk-step-scaling-cpu-{ENDPOINT}-AllTraffic" + assert alarm["AlarmActions"] == ["arn:policy/sagemaker-sdk-step-scaling-cpu"] + assert ( + alarm["MetricName"], + alarm["Threshold"], + alarm["EvaluationPeriods"], + alarm["DatapointsToAlarm"], + ) == ("CPUUtilization", 70, 3, 2) + assert alarm["Tags"] == OWNER_TAGS + + def test_percent_change_with_a_minimum_magnitude(self, run): + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=6, + policies=[ + StepScalingPolicy( + steps=[StepAdjustment(scaling_adjustment=50, lower_bound=0)], + alarm=Alarm( + metric=CustomMetric("Invocations", statistic="Sum", unit="Count"), + threshold=1000, + ), + adjustment_type="PercentChangeInCapacity", + min_adjustment_magnitude=2, + ) + ], + ) + config = aws.called("put_scaling_policy")[0]["StepScalingPolicyConfiguration"] + assert aws.called("put_metric_alarm")[0]["Unit"] == "Count" + assert (config["AdjustmentType"], config["MinAdjustmentMagnitude"]) == ( + "PercentChangeInCapacity", + 2, + ) + + @pytest.mark.parametrize( + "policy, message", + [ + (StepScalingPolicy(steps=[], alarm=Alarm(CustomMetric("X"), 1)), "at least one step"), + ( + StepScalingPolicy( + steps=[StepAdjustment(1, 0)], alarm=Alarm(CustomMetric("X"), 1), cooldown=-1 + ), + "cooldown", + ), + (TargetTrackingPolicy(target_value=0), "target_value"), + (TargetTrackingPolicy(target_value=True), "target_value"), + (TargetTrackingPolicy(target_value=4, scale_in_cooldown=-1), "scale_in_cooldown"), + ("not a policy", "policies must be"), + ], + ) + def test_bad_policies(self, run, policy, message): + aws = FakeAWS() + with pytest.raises(ValueError, match=message): + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + policies=[policy], + ) + assert aws.writes() == [] + + +class TestScheduledActions: + def test_puts_scheduled_actions_with_their_bounds_and_time_zone(self, run): + start = datetime(2026, 12, 1) + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + target_value=4, + scheduled_actions=[ + ScheduledAction( + name="morning", + schedule="cron(0 8 ? * MON-FRI *)", + min_capacity=2, + timezone="America/New_York", + start_time=start, + ), + ScheduledAction( + name="night", + schedule="cron(0 20 * * ? *)", + min_capacity=1, + max_capacity=2, + end_time=start, + ), + ], + ) + morning, night = aws.called("put_scheduled_action") + assert morning == { + "ServiceNamespace": "sagemaker", + "ResourceId": VARIANT_ID, + "ScalableDimension": "sagemaker:variant:DesiredInstanceCount", + "ScheduledActionName": "sagemaker-sdk-morning", + "Schedule": "cron(0 8 ? * MON-FRI *)", + "ScalableTargetAction": {"MinCapacity": 2}, + "Timezone": "America/New_York", + "StartTime": start, + } + assert night["ScalableTargetAction"] == {"MinCapacity": 1, "MaxCapacity": 2} + assert night["EndTime"] == start + + def test_scheduled_actions_alone(self, run): + aws = FakeAWS() + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + scheduled_actions=[ScheduledAction(name="a", schedule="rate(1 day)", max_capacity=3)], + ) + assert aws.called("put_scaling_policy") == [] + assert len(aws.called("put_scheduled_action")) == 1 + + @pytest.mark.parametrize( + "action, message", + [ + (ScheduledAction(name="a", schedule="every day", min_capacity=1), "at\\(...\\)"), + (ScheduledAction(name="a", schedule="rate(1 day)"), "min_capacity or max_capacity"), + (ScheduledAction(name="", schedule="rate(1 day)", min_capacity=1), "needs a name"), + (ScheduledAction(name="a", schedule="rate(1 day)", min_capacity=-1), "MinCapacity"), + ("not an action", "ScheduledAction objects"), + ], + ) + def test_bad_scheduled_actions(self, run, action, message): + aws = FakeAWS() + with pytest.raises(ValueError, match=message): + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + scheduled_actions=[action], + ) + assert aws.writes() == [] + + +class TestDeclarativeChanges: + def test_policies_and_schedules_no_longer_given_are_removed_and_others_stay(self, run): + aws = FakeAWS( + registered=(1, 4), + policies=(TRACKING, "sagemaker-sdk-step-scaling-cpu", "theirs"), + scheduled_actions=("sagemaker-sdk-old", "their-schedule"), + alarms={f"sagemaker-sdk-step-scaling-cpu-{ENDPOINT}-AllTraffic": ({}, OWNER_TAGS)}, + ) + result, _ = run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + target_value=4, + ) + assert [d["PolicyName"] for d in aws.called("delete_scaling_policy")] == [ + "sagemaker-sdk-step-scaling-cpu" + ] + assert aws.called("delete_alarms") == [ + {"AlarmNames": [f"sagemaker-sdk-step-scaling-cpu-{ENDPOINT}-AllTraffic"]} + ] + assert [d["ScheduledActionName"] for d in aws.called("delete_scheduled_action")] == [ + "sagemaker-sdk-old" + ] + assert {p["PolicyName"] for p in result["policies"]} == {TRACKING, "theirs"} + assert {a["ScheduledActionName"] for a in result["scheduled_actions"]} == {"their-schedule"} + + def test_entries_on_later_pages_are_seen(self, run): + # Many policies and schedules from elsewhere push the SDK's onto later pages. + others = tuple(f"theirs-{i}" for i in range(3)) + aws = FakeAWS( + registered=(1, 4), + policies=others + ("sagemaker-sdk-step-scaling-old",), + scheduled_actions=("their-schedule", "sagemaker-sdk-old"), + page_size=1, + ) + result, _ = run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + target_value=4, + ) + assert [d["PolicyName"] for d in aws.called("delete_scaling_policy")] == [ + "sagemaker-sdk-step-scaling-old" + ] + assert [d["ScheduledActionName"] for d in aws.called("delete_scheduled_action")] == [ + "sagemaker-sdk-old" + ] + assert {p["PolicyName"] for p in result["policies"]} == set(others) | {TRACKING} + + def test_an_alarm_it_did_not_create_is_left_alone(self, run): + name = f"sagemaker-sdk-step-scaling-cpu-{ENDPOINT}-AllTraffic" + aws = FakeAWS( + registered=(1, 4), + policies=("sagemaker-sdk-step-scaling-cpu",), + alarms={name: ({}, [{"Key": "team", "Value": "other"}])}, + ) + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=4, + target_value=4, + ) + assert aws.called("delete_alarms") == [] + + +class TestInferenceComponents: + def test_scales_the_copy_count_on_the_component_metric(self, run): + aws = _ic_aws(components={IC: {}, "adapter-1": {"base": IC}}) + run( + aws, + enable_autoscaling, + inference_component_name=IC, + min_capacity=1, + max_capacity=3, + target_value=4, + ) + (register,) = aws.called("register_scalable_target") + assert (register["ResourceId"], register["ScalableDimension"]) == ( + IC_ID, + "sagemaker:inference-component:DesiredCopyCount", + ) + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["PredefinedMetricSpecification"] == { + "PredefinedMetricType": "SageMakerInferenceComponentConcurrentRequestsPerCopyHighResolution" + } + + def test_a_custom_metric_uses_the_component_dimension(self, run): + aws = _ic_aws() + run( + aws, + enable_autoscaling, + inference_component_name=IC, + min_capacity=1, + max_capacity=3, + target_value=70, + metric=CustomMetric("GPUUtilizationNormalized"), + ) + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["CustomizedMetricSpecification"]["Dimensions"] == [ + {"Name": "InferenceComponentName", "Value": IC} + ] + + def test_scale_to_zero_lowers_the_minimum_only_after_the_alarm_exists(self, run): + aws = _zero_ic_aws() + result, _ = run( + aws, + enable_autoscaling, + inference_component_name=IC, + min_capacity=0, + max_capacity=2, + target_value=4, + scale_to_zero=True, + ) + assert [r.get("MinCapacity") for r in aws.called("register_scalable_target")] == [1, 0] + writes = aws.writes() + assert writes.index("put_metric_alarm") < len(writes) - 1 - writes[::-1].index( + "register_scalable_target" + ) + step = _policy(aws, FROM_ZERO) + assert step["StepScalingPolicyConfiguration"] == { + "AdjustmentType": "ChangeInCapacity", + "MetricAggregationType": "Maximum", + "Cooldown": 60, + "StepAdjustments": [{"ScalingAdjustment": 1, "MetricIntervalLowerBound": 0}], + } + (alarm,) = aws.called("put_metric_alarm") + assert alarm["AlarmName"] == IC_FROM_ZERO_ALARM + assert alarm["AlarmActions"] == [f"arn:policy/{FROM_ZERO}"] + assert (alarm["Namespace"], alarm["MetricName"], alarm["Statistic"]) == ( + "AWS/SageMaker", + "NoCapacityInvocationFailures", + "Sum", + ) + assert alarm["Dimensions"] == [{"Name": "InferenceComponentName", "Value": IC}] + assert alarm["TreatMissingData"] == "notBreaching" + assert result["scalable_target"]["MinCapacity"] == 0 + + def test_a_failed_alarm_write_leaves_a_minimum_of_one(self, run): + aws = _zero_ic_aws() + aws.cloudwatch.put_metric_alarm.side_effect = RuntimeError("AccessDenied") + with pytest.raises(RuntimeError): + run( + aws, + enable_autoscaling, + inference_component_name=IC, + min_capacity=0, + max_capacity=2, + target_value=4, + scale_to_zero=True, + ) + assert aws.target["MinCapacity"] == 1 + + def test_scale_to_zero_already_at_zero_registers_once(self, run): + aws = _zero_ic_aws( + registered=(0, 2), + policies=(TRACKING, FROM_ZERO), + alarms={IC_FROM_ZERO_ALARM: ({}, OWNER_TAGS)}, + ) + run( + aws, + enable_autoscaling, + inference_component_name=IC, + min_capacity=0, + max_capacity=3, + target_value=4, + scale_to_zero=True, + ) + assert [r["MinCapacity"] for r in aws.called("register_scalable_target")] == [0] + + def test_a_change_away_from_zero_deletes_the_step_policy_and_alarm(self, run): + aws = _ic_aws( + registered=(0, 2), + policies=(TRACKING, FROM_ZERO), + alarms={IC_FROM_ZERO_ALARM: ({}, OWNER_TAGS)}, + ) + result, _ = run( + aws, + enable_autoscaling, + inference_component_name=IC, + min_capacity=1, + max_capacity=2, + target_value=4, + ) + assert [d["PolicyName"] for d in aws.called("delete_scaling_policy")] == [FROM_ZERO] + assert aws.called("delete_alarms") == [{"AlarmNames": [IC_FROM_ZERO_ALARM]}] + assert [p["PolicyName"] for p in result["policies"]] == [TRACKING] + + +class TestAsynchronousAndServerless: + def test_an_asynchronous_endpoint_tracks_its_backlog_and_can_reach_zero(self, run): + aws = FakeAWS(async_config={"OutputConfig": {"S3OutputPath": "s3://b/o"}}) + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=0, + max_capacity=3, + target_value=5, + ) + assert aws.called("register_scalable_target")[0]["MinCapacity"] == 0 + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["CustomizedMetricSpecification"] == { + "MetricName": "ApproximateBacklogSizePerInstance", + "Namespace": "AWS/SageMaker", + "Dimensions": [{"Name": "EndpointName", "Value": ENDPOINT}], + "Statistic": "Average", + } + + def test_asynchronous_scale_to_zero_scales_out_on_backlog_without_capacity(self, run): + aws = FakeAWS(async_config={"OutputConfig": {"S3OutputPath": "s3://b/o"}}) + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=0, + max_capacity=3, + target_value=5, + scale_to_zero=True, + ) + assert [r["MinCapacity"] for r in aws.called("register_scalable_target")] == [0] + (alarm,) = aws.called("put_metric_alarm") + assert (alarm["MetricName"], alarm["EvaluationPeriods"], alarm["DatapointsToAlarm"]) == ( + "HasBacklogWithoutCapacity", + 2, + 2, + ) + assert alarm["Dimensions"] == [{"Name": "EndpointName", "Value": ENDPOINT}] + assert _policy(aws, FROM_ZERO)["PolicyType"] == "StepScaling" + + def test_serverless_provisioned_concurrency(self, run): + aws = FakeAWS( + serverless={"MemorySizeInMB": 2048, "MaxConcurrency": 20, "ProvisionedConcurrency": 2} + ) + run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=10, + target_value=0.5, + ) + assert aws.called("register_scalable_target")[0]["ScalableDimension"] == ( + "sagemaker:variant:DesiredProvisionedConcurrency" + ) + spec = aws.called("put_scaling_policy")[0]["TargetTrackingScalingPolicyConfiguration"] + assert spec["PredefinedMetricSpecification"]["PredefinedMetricType"] == ( + "SageMakerVariantProvisionedConcurrencyUtilization" + ) + + +def _refuses(run, aws, message, **kwargs): + with pytest.raises(ValueError, match=message): + run(aws, enable_autoscaling, **kwargs) + assert aws.writes() == [] + + +class TestRefusesBeforeWriting: + @pytest.mark.parametrize( + "kwargs, message", + [ + (dict(min_capacity=0, max_capacity=2, target_value=4), "min_capacity must be"), + (dict(min_capacity=3, max_capacity=2, target_value=4), "must not exceed"), + (dict(min_capacity=True, max_capacity=2, target_value=4), "min_capacity"), + (dict(min_capacity=1, max_capacity=0, target_value=4), "max_capacity"), + (dict(min_capacity=1, max_capacity=2, target_value=4, metric="cpu"), "does not apply"), + ( + dict(min_capacity=1, max_capacity=2, target_value=4, metric="backlog-per-instance"), + "asynchronous endpoint", + ), + ( + dict(min_capacity=0, max_capacity=2, target_value=4, scale_to_zero=True), + "real-time production variant", + ), + (dict(min_capacity=1, max_capacity=2), "Pass target_value"), + ( + dict(min_capacity=1, max_capacity=2, metric="invocations"), + "metric needs a target_value", + ), + ( + dict( + min_capacity=1, + max_capacity=2, + target_value=4, + policies=[TargetTrackingPolicy(target_value=4)], + ), + "not both", + ), + ], + ) + def test_bad_arguments(self, run, kwargs, message): + _refuses(run, FakeAWS(), message, endpoint_name=ENDPOINT, **kwargs) + + def test_no_target_named(self, run): + _refuses( + run, FakeAWS(), "Pass endpoint_name", min_capacity=1, max_capacity=2, target_value=4 + ) + + @pytest.mark.parametrize( + "aws_kwargs, message", + [ + (dict(status="Updating"), "not InService"), + (dict(serverless={"MaxConcurrency": 5}), "without provisioned concurrency"), + (dict(variants=("A", "B")), "pass variant_name"), + (dict(model_name=None), "pass inference_component_name"), + ], + ) + def test_endpoints_that_cannot_scale_this_way(self, run, aws_kwargs, message): + _refuses( + run, + FakeAWS(**aws_kwargs), + message, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=4, + ) + + def test_provisioned_concurrency_does_not_scale_to_zero(self, run): + aws = FakeAWS(serverless={"MaxConcurrency": 5, "ProvisionedConcurrency": 1}) + _refuses( + run, + aws, + "does not scale to zero", + endpoint_name=ENDPOINT, + min_capacity=0, + max_capacity=2, + target_value=0.5, + scale_to_zero=True, + ) + + def test_an_unknown_variant(self, run): + _refuses( + run, + FakeAWS(), + "no variant 'B'", + endpoint_name=ENDPOINT, + variant_name="B", + min_capacity=1, + max_capacity=2, + target_value=4, + ) + + def test_a_component_without_managed_instance_scaling(self, run): + _refuses( + run, + _ic_aws(managed={"Status": "DISABLED"}), + "no managed instance scaling", + inference_component_name=IC, + min_capacity=1, + max_capacity=2, + target_value=4, + ) + + def test_an_adapter_names_its_base(self, run): + aws = _ic_aws(components={IC: {}, "adapter-1": {"base": IC}}) + _refuses( + run, + aws, + f"inference_component_name='{IC}'", + inference_component_name="adapter-1", + min_capacity=1, + max_capacity=2, + target_value=4, + ) + + def test_a_component_on_another_endpoint(self, run): + _refuses( + run, + _ic_aws(components={IC: {"endpoint": "other"}}), + "not my-endpoint", + endpoint_name=ENDPOINT, + inference_component_name=IC, + min_capacity=1, + max_capacity=2, + target_value=4, + ) + + def test_invocations_on_a_base_with_adapters(self, run): + aws = _ic_aws(components={IC: {}, "adapter-1": {"base": IC}}) + _refuses( + run, + aws, + "concurrent-requests", + inference_component_name=IC, + min_capacity=1, + max_capacity=2, + target_value=4, + metric="invocations", + ) + + def test_scale_to_zero_on_a_component(self, run): + _refuses( + run, + _ic_aws(), + "MinInstanceCount 0", + inference_component_name=IC, + min_capacity=0, + max_capacity=2, + target_value=4, + scale_to_zero=True, + ) + _refuses( + run, + _zero_ic_aws(), + "min_capacity=0", + inference_component_name=IC, + min_capacity=1, + max_capacity=2, + target_value=4, + scale_to_zero=True, + ) + aws = _zero_ic_aws(components={IC: {}, "adapter-1": {"base": IC}}) + _refuses( + run, + aws, + "adapters", + inference_component_name=IC, + min_capacity=0, + max_capacity=2, + target_value=4, + scale_to_zero=True, + ) + + def test_a_component_without_scale_to_zero_keeps_a_minimum_of_one(self, run): + _refuses( + run, + _zero_ic_aws(), + "min_capacity must be", + inference_component_name=IC, + min_capacity=0, + max_capacity=2, + target_value=4, + ) + + +class TestDisable: + def test_deregisters_a_target_it_registered_and_deletes_its_alarms(self, run): + aws = _ic_aws( + registered=(0, 2), + policies=(TRACKING, FROM_ZERO), + scheduled_actions=("sagemaker-sdk-night",), + alarms={IC_FROM_ZERO_ALARM: ({}, OWNER_TAGS)}, + ) + result, _ = run(aws, disable_autoscaling, inference_component_name=IC) + assert len(aws.called("deregister_scalable_target")) == 1 + assert aws.called("delete_alarms") == [{"AlarmNames": [IC_FROM_ZERO_ALARM]}] + assert result["deregistered"] is True + assert result["deleted_policies"] == sorted([TRACKING, FROM_ZERO]) + assert result["deleted_scheduled_actions"] == ["sagemaker-sdk-night"] + assert result["remaining"]["scalable_target"] is None + + def test_a_target_it_did_not_register_stays(self, run): + aws = FakeAWS( + registered=(1, 2), + ours=False, + policies=(TRACKING,), + scheduled_actions=("sagemaker-sdk-night",), + ) + result, _ = run(aws, disable_autoscaling, endpoint_name=ENDPOINT) + assert aws.called("deregister_scalable_target") == [] + assert [d["PolicyName"] for d in aws.called("delete_scaling_policy")] == [TRACKING] + assert [d["ScheduledActionName"] for d in aws.called("delete_scheduled_action")] == [ + "sagemaker-sdk-night" + ] + assert result["remaining"]["scalable_target"] is not None + + def test_other_policies_and_scheduled_actions_keep_the_target(self, run): + for extra in ( + dict(policies=(TRACKING, "theirs")), + dict(policies=(TRACKING,), scheduled_actions=("nightly",)), + ): + aws = FakeAWS(registered=(1, 2), **extra) + result, _ = run(aws, disable_autoscaling, endpoint_name=ENDPOINT) + assert aws.called("deregister_scalable_target") == [] + assert [d["PolicyName"] for d in aws.called("delete_scaling_policy")] == [TRACKING] + assert result["deregistered"] is False + + def test_runs_while_the_endpoint_updates_or_after_managed_scaling_is_off(self, run): + aws = _ic_aws(status="Updating", managed=None, registered=(1, 2), policies=(TRACKING,)) + result, _ = run(aws, disable_autoscaling, inference_component_name=IC) + assert result["deregistered"] is True + + def test_nothing_registered_changes_nothing(self, run): + aws = FakeAWS() + result, _ = run(aws, disable_autoscaling, endpoint_name=ENDPOINT) + assert aws.writes() == [] + assert (result["deregistered"], result["deleted_policies"]) == (False, []) + + def test_warns_when_a_target_has_nothing_it_created(self, run): + aws = FakeAWS(registered=(1, 2), ours=False, policies=("theirs",)) + with patch.object(autoscaling.logger, "warning") as warning: + result, _ = run(aws, disable_autoscaling, endpoint_name=ENDPOINT, wait=False) + assert aws.writes() == [] + assert "nothing was deleted" in warning.call_args[0][0] + assert [p["PolicyName"] for p in result["remaining"]["policies"]] == ["theirs"] + + +class TestSuspendResume: + def test_suspend_and_resume_set_the_suspended_state(self, run): + aws = FakeAWS(registered=(1, 2), policies=(TRACKING,)) + result, _ = run(aws, suspend_autoscaling, endpoint_name=ENDPOINT, scheduled=False) + assert aws.called("register_scalable_target")[-1]["SuspendedState"] == { + "DynamicScalingInSuspended": True, + "DynamicScalingOutSuspended": True, + "ScheduledScalingSuspended": False, + } + assert "MinCapacity" not in aws.called("register_scalable_target")[-1] + assert result["scalable_target"]["SuspendedState"]["DynamicScalingInSuspended"] is True + result, _ = run(aws, resume_autoscaling, endpoint_name=ENDPOINT) + assert set(result["scalable_target"]["SuspendedState"].values()) == {False} + + def test_an_unregistered_target_cannot_be_suspended(self, run): + aws = FakeAWS() + with pytest.raises(ValueError, match="not registered"): + run(aws, suspend_autoscaling, endpoint_name=ENDPOINT) + assert aws.writes() == [] + + +class TestReadBack: + def test_retries_until_the_write_reads_back(self, run): + aws = FakeAWS() + reads = {"n": 0} + real = aws.autoscaling.describe_scalable_targets.side_effect + + def lagging(*args, **kwargs): + reads["n"] += 1 + # The first read is before the write; the next two lag behind it. + return {"ScalableTargets": []} if 1 < reads["n"] <= 3 else real(*args, **kwargs) + + aws.autoscaling.describe_scalable_targets.side_effect = lagging + result, sleep = run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=4, + ) + assert sleep.call_count == 2 + assert result["scalable_target"] is not None + + def test_warns_when_the_write_never_reads_back(self, run): + aws = FakeAWS() + aws.autoscaling.describe_scalable_targets.side_effect = lambda **kw: {"ScalableTargets": []} + with patch.object(autoscaling.logger, "warning") as warning: + result, sleep = run( + aws, + enable_autoscaling, + endpoint_name=ENDPOINT, + min_capacity=1, + max_capacity=2, + target_value=4, + ) + assert sleep.call_count == autoscaling._READ_BACK_ATTEMPTS - 1 + assert "does not read back yet" in warning.call_args[0][0] + assert result["scalable_target"] is None + + +def test_describe_returns_target_policies_and_scheduled_actions(run): + aws = FakeAWS(registered=(1, 3), policies=(TRACKING,), scheduled_actions=("nightly",)) + result, _ = run(aws, describe_autoscaling, endpoint_name=ENDPOINT) + assert result["resource_id"] == VARIANT_ID + assert result["scalable_target"]["MaxCapacity"] == 3 + assert [p["PolicyName"] for p in result["policies"]] == [TRACKING] + assert result["scheduled_actions"] == [{"ScheduledActionName": "nightly"}] + assert aws.writes() == [] + + +def test_a_target_without_an_arn_is_not_treated_as_its_own(): + assert autoscaling._is_ours(Mock(), {"MinCapacity": 1}) is False + + +def test_clients_come_from_the_session_region(): + session = Mock(boto_region_name="eu-west-1") + clients = autoscaling._Clients(session) + assert clients.sagemaker is session.sagemaker_client + session.boto_session.client.assert_any_call("application-autoscaling", region_name="eu-west-1") + session.boto_session.client.assert_any_call("cloudwatch", region_name="eu-west-1") diff --git a/sagemaker-serve/tests/unit/test_model_customization_managed_instance_scaling.py b/sagemaker-serve/tests/unit/test_model_customization_managed_instance_scaling.py new file mode 100644 index 0000000000..e5a87c2e9a --- /dev/null +++ b/sagemaker-serve/tests/unit/test_model_customization_managed_instance_scaling.py @@ -0,0 +1,216 @@ +"""Unit tests for managed_instance_scaling on the model customization deploy path.""" + +import unittest +from unittest.mock import Mock, patch + +from sagemaker.core.compute_resource_requirements.resource_requirements import ResourceRequirements +from sagemaker.core.utils.utils import Unassigned, serialize +from sagemaker.serve.mode.function_pointers import Mode +from sagemaker.serve.model_builder import ModelBuilder + + +def _patches(func): + for target in ( + "sagemaker.serve.model_builder.ModelBuilder._is_nova_model", + "sagemaker.core.resources.InferenceComponent.get_all", + "sagemaker.core.resources.InferenceComponent.create", + "sagemaker.core.resources.Endpoint.get", + "sagemaker.core.resources.Endpoint.create", + "sagemaker.core.resources.EndpointConfig.create", + "sagemaker.serve.model_builder.ModelBuilder._does_endpoint_exist", + "sagemaker.serve.model_builder.ModelBuilder._fetch_model_package", + "sagemaker.serve.model_builder.ModelBuilder._fetch_peft", + "sagemaker.serve.model_builder.ModelBuilder._fetch_model_package_arn", + "sagemaker.core.resources.Association.add", + "sagemaker.core.resources.Artifact.get_all", + "sagemaker.core.resources.Action.create", + "sagemaker.core.resources.InferenceComponent.get", + ): + func = patch(target)(func) + return func + + +ENDPOINT_CREATE, CONFIG_CREATE = 4, 5 + + +class TestModelCustomizationManagedInstanceScaling(unittest.TestCase): + def setUp(self): + self.session = Mock() + self.session.boto_region_name = "us-west-2" + self.session.default_bucket.return_value = "test-bucket" + self.session.default_bucket_prefix = "test-prefix" + self.session.config = {} + self.session.sagemaker_config = {} + self.session.settings = Mock() + self.session.settings.include_jumpstart_tags = False + credentials = Mock(access_key="test-key", secret_key="test-secret", token=None) + self.session.boto_session = Mock(region_name="us-west-2") + self.session.boto_session.get_credentials.return_value = credentials + + def _deploy(self, mocks, endpoint_exists=False, inference_component=True, **deploy_kwargs): + # patch() decorators applied first come first: see _patches. + ( + is_nova, + _ic_get_all, + _ic_create, + _endpoint_get, + endpoint_create, + _config_create, + does_endpoint_exist, + fetch_package, + fetch_peft, + fetch_package_arn, + _association_add, + artifact_get_all, + _action_create, + ic_get, + ) = mocks + is_nova.return_value = False + package = Mock() + package.model_package_arn = "arn:aws:sagemaker:us-west-2:123456789012:model-package/p" + package.inference_specification.containers = [Mock()] + package.inference_specification.containers[0].base_model.recipe_name = "test-recipe" + package.inference_specification.containers[0].model_data_source.s3_data_source.s3_uri = ( + "s3://test-bucket/model" + ) + fetch_package.return_value = package + fetch_peft.return_value = "FULL" + does_endpoint_exist.return_value = endpoint_exists + endpoint_create.return_value = Mock(wait_for_status=Mock()) + ic_get.return_value = Mock( + inference_component_arn="arn:aws:sagemaker:us-west-2:123456789012:inference-component/c" + ) + fetch_package_arn.return_value = package.model_package_arn + artifact_get_all.return_value = [ + Mock(artifact_arn="arn:aws:sagemaker:us-west-2:123456789012:artifact/a") + ] + builder = ModelBuilder( + model="huggingface-llm-mistral-7b", + model_metadata={ + "CUSTOM_MODEL_ID": "huggingface-llm-mistral-7b", + "CUSTOM_MODEL_VERSION": "1.0.0", + }, + instance_type="ml.g5.12xlarge", + mode=Mode.SAGEMAKER_ENDPOINT, + role_arn="arn:aws:iam::123456789012:role/TestRole", + sagemaker_session=self.session, + image_uri="123456789012.dkr.ecr.us-west-2.amazonaws.com/test:latest", + ) + builder.built_model = Mock(model_name="test-model") + if inference_component: + deploy_kwargs["inference_config"] = ResourceRequirements( + requests={"num_cpus": 4, "memory": 8192} + ) + builder._deploy_model_customization(endpoint_name="test-endpoint", **deploy_kwargs) + + @staticmethod + def _variant(config_create): + (variant,) = config_create.call_args[1]["production_variants"] + return variant + + @_patches + def test_sets_managed_instance_scaling_on_a_new_endpoint_configuration(self, *mocks): + self._deploy(mocks, managed_instance_scaling={"MinInstanceCount": 1, "MaxInstanceCount": 4}) + scaling = self._variant(mocks[CONFIG_CREATE]).managed_instance_scaling + assert (scaling.status, scaling.min_instance_count, scaling.max_instance_count) == ( + "ENABLED", + 1, + 4, + ) + + @_patches + def test_min_instance_count_defaults_to_the_initial_instance_count(self, *mocks): + self._deploy( + mocks, initial_instance_count=2, managed_instance_scaling={"MaxInstanceCount": 4} + ) + assert self._variant(mocks[CONFIG_CREATE]).managed_instance_scaling.min_instance_count == 2 + + @_patches + def test_no_managed_instance_scaling_unless_requested(self, *mocks): + self._deploy(mocks) + assert isinstance(self._variant(mocks[CONFIG_CREATE]).managed_instance_scaling, Unassigned) + + @_patches + def test_an_existing_endpoint_keeps_its_configuration(self, *mocks): + with patch("sagemaker.serve.model_builder.logger") as logger: + self._deploy( + mocks, + endpoint_exists=True, + managed_instance_scaling={"MinInstanceCount": 1, "MaxInstanceCount": 4}, + ) + assert not mocks[CONFIG_CREATE].called + assert any("already exists" in c.args[0] for c in logger.warning.call_args_list) + + @_patches + def test_a_minimum_of_zero_reaches_the_request(self, *mocks): + # Scale to zero: sagemaker-core keeps a 0 when it serializes the shape. + self._deploy(mocks, managed_instance_scaling={"MinInstanceCount": 0, "MaxInstanceCount": 2}) + scaling = self._variant(mocks[CONFIG_CREATE]).managed_instance_scaling + assert serialize(scaling) == { + "Status": "ENABLED", + "MinInstanceCount": 0, + "MaxInstanceCount": 2, + } + + @_patches + def test_a_missing_maximum_is_refused_before_anything_is_created(self, *mocks): + with self.assertRaisesRegex(ValueError, "MaxInstanceCount"): + self._deploy(mocks, managed_instance_scaling={"MinInstanceCount": 1}) + assert not mocks[CONFIG_CREATE].called + with self.assertRaisesRegex(ValueError, "MaxInstanceCount"): + self._deploy( + mocks, managed_instance_scaling={"MinInstanceCount": 3, "MaxInstanceCount": 2} + ) + + @_patches + def test_a_restricted_package_on_the_variant_warns_that_it_is_ignored(self, *mocks): + with patch( + "sagemaker.serve.utils.model_package_utils.is_restricted_model_package", + return_value=True, + ), patch("sagemaker.serve.model_builder.logger") as logger: + self._deploy( + mocks, + inference_component=False, + managed_instance_scaling={"MinInstanceCount": 1, "MaxInstanceCount": 2}, + ) + (variant,) = mocks[CONFIG_CREATE].call_args[1]["production_variants"] + assert isinstance(variant.managed_instance_scaling, Unassigned) + assert any("restricted model package" in c.args[1] for c in logger.warning.call_args_list) + + @_patches + def test_a_nova_model_on_the_variant_warns_that_it_is_ignored(self, *mocks): + mocks[0].return_value = True # _is_nova_model + with patch.object(ModelBuilder, "_deploy_nova_model") as deploy_nova, patch( + "sagemaker.serve.model_builder.logger" + ) as logger: + self._deploy_nova(mocks) + assert deploy_nova.called + assert any("Nova model" in c.args[1] for c in logger.warning.call_args_list) + + def _deploy_nova(self, mocks): + builder = ModelBuilder( + model="huggingface-llm-mistral-7b", + model_metadata={ + "CUSTOM_MODEL_ID": "huggingface-llm-mistral-7b", + "CUSTOM_MODEL_VERSION": "1.0.0", + }, + instance_type="ml.g5.12xlarge", + mode=Mode.SAGEMAKER_ENDPOINT, + role_arn="arn:aws:iam::123456789012:role/TestRole", + sagemaker_session=self.session, + image_uri="123456789012.dkr.ecr.us-west-2.amazonaws.com/test:latest", + ) + builder.built_model = Mock(model_name="test-model") + builder._deploy_model_customization( + endpoint_name="test-endpoint", + managed_instance_scaling={"MinInstanceCount": 1, "MaxInstanceCount": 2}, + ) + + def test_nothing_is_said_when_managed_instance_scaling_is_not_requested(self): + with patch("sagemaker.serve.model_builder.logger") as logger: + ModelBuilder._warn_managed_instance_scaling_ignored({}, "x") + assert not logger.warning.called + + +if __name__ == "__main__": + unittest.main()