forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodel_builder.py
More file actions
4954 lines (4352 loc) · 222 KB
/
model_builder.py
File metadata and controls
4954 lines (4352 loc) · 222 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
"""ModelBuilder class for building and deploying machine learning models.
Provides a unified interface for building and deploying ML models across different
model servers and deployment modes.
"""
from __future__ import absolute_import, annotations
import json
import re
import os
import copy
import logging
import uuid
import platform
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Union, Set
from botocore.exceptions import ClientError
import packaging.version
from sagemaker.core.resources import (
Model,
Endpoint,
TrainingJob,
HubContent,
InferenceComponent,
EndpointConfig,
)
from sagemaker.core.shapes import (
ContainerDefinition,
ModelMetrics,
MetadataProperties,
ModelLifeCycle,
DriftCheckBaselines,
InferenceComponentComputeResourceRequirements,
InferenceComponentDataCacheConfig,
InferenceComponentContainerSpecification,
)
from sagemaker.core.resources import (
ModelPackage,
ModelPackageGroup,
ModelCard,
ModelPackageModelCard,
)
from sagemaker.core.utils.utils import logger
from sagemaker.core.helper import session_helper
from sagemaker.core.helper.session_helper import (
Session,
get_execution_role,
_wait_until,
_deploy_done,
)
from sagemaker.core.helper.pipeline_variable import StrPipeVar, PipelineVariable
from sagemaker.train.model_trainer import ModelTrainer
from sagemaker.core.training.configs import Compute, Networking, SourceCode
from sagemaker.serve.spec.inference_spec import InferenceSpec
from sagemaker.serve.local_resources import LocalEndpoint
from sagemaker.serve.spec.inference_base import AsyncCustomOrchestrator, CustomOrchestrator
from sagemaker.serve.builder.schema_builder import SchemaBuilder
from sagemaker.core.transformer import Transformer
from sagemaker.serve.mode.function_pointers import Mode
from sagemaker.serve.mode.local_container_mode import LocalContainerMode
from sagemaker.serve.mode.sagemaker_endpoint_mode import SageMakerEndpointMode
from sagemaker.serve.mode.in_process_mode import InProcessMode
from sagemaker.serve.utils.types import ModelServer, ModelHub
from sagemaker.serve.detector.image_detector import _get_model_base, _detect_framework_and_version
from sagemaker.serve.detector.pickler import save_pkl, save_xgboost
from sagemaker.serve.validations.check_image_uri import is_1p_image_uri
from sagemaker.core.inference_config import ResourceRequirements
from sagemaker.serve.inference_recommendation_mixin import _InferenceRecommenderMixin
from sagemaker.serve.model_builder_utils import _ModelBuilderUtils
from sagemaker.serve.model_builder_servers import _ModelBuilderServers
from sagemaker.serve.validations.optimization import _validate_optimization_configuration
from sagemaker.core.enums import Tag
from sagemaker.core.model_registry import (
get_model_package_args,
create_model_package_from_containers,
)
from sagemaker.core.jumpstart.enums import JumpStartModelType
from sagemaker.core.jumpstart.configs import JumpStartConfig
from sagemaker.core.jumpstart.utils import add_jumpstart_uri_tags
from sagemaker.core.jumpstart.artifacts.kwargs import _retrieve_model_deploy_kwargs
from sagemaker.core.inference_config import AsyncInferenceConfig, ServerlessInferenceConfig
from sagemaker.serve.batch_inference.batch_transform_inference_config import (
BatchTransformInferenceConfig,
)
from sagemaker.core.serializers import (
NumpySerializer,
TorchTensorSerializer,
)
from sagemaker.core.deserializers import (
JSONDeserializer,
TorchTensorDeserializer,
)
from sagemaker.core import s3
from sagemaker.core.explainer.explainer_config import ExplainerConfig
from sagemaker.core.enums import EndpointType
from sagemaker.core.common_utils import (
Tags,
ModelApprovalStatusEnum,
_resolve_routing_config,
format_tags,
resolve_value_from_config,
unique_name_from_base,
name_from_base,
base_from_name,
to_string,
base_name_from_image,
resolve_nested_dict_value_from_config,
get_config_value,
repack_model,
update_container_with_inference_params,
)
from sagemaker.core.config.config_schema import (
MODEL_ENABLE_NETWORK_ISOLATION_PATH,
MODEL_EXECUTION_ROLE_ARN_PATH,
MODEL_VPC_CONFIG_PATH,
ENDPOINT_CONFIG_ASYNC_KMS_KEY_ID_PATH,
MODEL_CONTAINERS_PATH,
)
from sagemaker.serve.constants import LOCAL_MODES, SUPPORTED_MODEL_SERVERS, Framework
from sagemaker.core.workflow.pipeline_context import PipelineSession, runnable_by_pipeline
from sagemaker.core import fw_utils
from sagemaker.core.helper.session_helper import container_def
from sagemaker.core.workflow import is_pipeline_variable
from sagemaker.core import image_uris
from sagemaker.core.fw_utils import model_code_key_prefix
from sagemaker.train.base_trainer import BaseTrainer
from sagemaker.core.telemetry.telemetry_logging import _telemetry_emitter
from sagemaker.core.telemetry.constants import Feature
_LOWEST_MMS_VERSION = "1.2"
SCRIPT_PARAM_NAME = "sagemaker_program"
DIR_PARAM_NAME = "sagemaker_submit_directory"
CONTAINER_LOG_LEVEL_PARAM_NAME = "sagemaker_container_log_level"
JOB_NAME_PARAM_NAME = "sagemaker_job_name"
MODEL_SERVER_WORKERS_PARAM_NAME = "sagemaker_model_server_workers"
SAGEMAKER_REGION_PARAM_NAME = "sagemaker_region"
SAGEMAKER_OUTPUT_LOCATION = "sagemaker_s3_output"
@dataclass
class ModelBuilder(_InferenceRecommenderMixin, _ModelBuilderServers, _ModelBuilderUtils):
"""Unified interface for building and deploying machine learning models.
ModelBuilder provides a streamlined workflow for preparing and deploying ML models to
Amazon SageMaker. It supports multiple frameworks (PyTorch, TensorFlow, HuggingFace, etc.),
model servers (TorchServe, TGI, Triton, etc.), and deployment modes (SageMaker endpoints,
local containers, in-process).
The typical workflow involves three steps:
1. Initialize ModelBuilder with your model and configuration
2. Call build() to create a deployable Model resource
3. Call deploy() to create an Endpoint resource for inference
Example:
>>> from sagemaker.serve.model_builder import ModelBuilder
>>> from sagemaker.serve.mode.function_pointers import Mode
>>>
>>> # Initialize with a trained model
>>> model_builder = ModelBuilder(
... model=my_pytorch_model,
... role_arn="arn:aws:iam::123456789012:role/SageMakerRole",
... instance_type="ml.m5.xlarge"
... )
>>>
>>> # Build the model (creates SageMaker Model resource)
>>> model = model_builder.build()
>>>
>>> # Deploy to endpoint (creates SageMaker Endpoint resource)
>>> endpoint = model_builder.deploy(endpoint_name="my-endpoint")
>>>
>>> # Make predictions
>>> result = endpoint.invoke(data=input_data)
Args:
model: The model to deploy. Can be a trained model object, ModelTrainer, TrainingJob,
ModelPackage, or JumpStart model ID string. Either model or inference_spec is required.
model_path: Local directory path where model artifacts are stored or will be downloaded.
inference_spec: Custom inference specification with load() and invoke() functions.
schema_builder: Defines input/output schema for serialization and deserialization.
modelbuilder_list: List of ModelBuilder objects for multi-model deployments.
pipeline_models: List of Model objects for creating inference pipelines.
role_arn: IAM role ARN for SageMaker to assume.
sagemaker_session: Session object for managing SageMaker API interactions.
image_uri: Container image URI. Auto-selected if not specified.
s3_model_data_url: S3 URI where model artifacts are stored or will be uploaded.
source_code: Source code configuration for custom inference code.
env_vars: Environment variables to set in the container.
model_server: Model server to use (TORCHSERVE, TGI, TRITON, etc.).
model_metadata: Dictionary to override model metadata (HF_TASK, MLFLOW_MODEL_PATH, etc.).
log_level: Logging level for ModelBuilder operations (default: logging.DEBUG).
content_type: MIME type of input data. Auto-derived from schema_builder if provided.
accept_type: MIME type of output data. Auto-derived from schema_builder if provided.
compute: Compute configuration specifying instance type and count.
network: Network configuration including VPC settings and network isolation.
instance_type: EC2 instance type for deployment (e.g., 'ml.m5.large').
mode: Deployment mode (SAGEMAKER_ENDPOINT, LOCAL_CONTAINER, or IN_PROCESS).
Note:
ModelBuilder returns sagemaker.core.resources.Model and sagemaker.core.resources.Endpoint
objects, not the deprecated PySDK Model and Predictor classes. Use endpoint.invoke()
instead of predictor.predict() for inference.
"""
# ========================================
# Core Model Definition
# ========================================
model: Optional[
Union[object, str, ModelTrainer, BaseTrainer, TrainingJob, ModelPackage, List[Model]]
] = field(
default=None,
metadata={
"help": "The model object, JumpStart model ID, or training job from which to extract "
"model artifacts. Can be a trained model object, ModelTrainer, TrainingJob, "
"ModelPackage, JumpStart model ID string, or list of core models. Either model or inference_spec is required."
},
)
model_path: Optional[str] = field(
default_factory=lambda: "/tmp/sagemaker/model-builder/" + uuid.uuid1().hex,
metadata={
"help": "Local directory path where model artifacts are stored or will be downloaded. "
"Defaults to a temporary directory under /tmp/sagemaker/model-builder/."
},
)
inference_spec: Optional[InferenceSpec] = field(
default=None,
metadata={
"help": "Custom inference specification with load() and invoke() functions for "
"model loading and inference logic. Either model or inference_spec is required."
},
)
schema_builder: Optional[SchemaBuilder] = field(
default=None,
metadata={
"help": "Defines the input/output schema for the model. The schema builder handles "
"serialization and deserialization of data between client and server. Can be omitted "
"for certain HuggingFace models with supported task types."
},
)
modelbuilder_list: Optional[List["ModelBuilder"]] = field(
default=None,
metadata={
"help": "List of ModelBuilder objects for multi-model or inference component deployments. "
"Used when deploying multiple models to a single endpoint."
},
)
role_arn: Optional[str] = field(
default=None,
metadata={
"help": "IAM role ARN for SageMaker to assume when creating models and endpoints. "
"If not specified, attempts to use the default SageMaker execution role."
},
)
sagemaker_session: Optional[Session] = field(
default=None,
metadata={
"help": "Session object for managing interactions with SageMaker APIs and AWS services. "
"If not specified, creates a session using the default AWS configuration."
},
)
image_uri: Optional[StrPipeVar] = field(
default=None,
metadata={
"help": "Container image URI for the model. If not specified, automatically selects "
"an appropriate SageMaker-provided container based on framework and model server."
},
)
s3_model_data_url: Optional[Union[str, PipelineVariable, Dict[str, Any]]] = field(
default=None,
metadata={
"help": "S3 URI where model artifacts are stored or will be uploaded. If not specified, "
"model artifacts are uploaded to a default S3 location."
},
)
source_code: Optional[SourceCode] = field(
default=None,
metadata={
"help": "Source code configuration for custom inference code, including source directory, "
"entry point script, and dependencies."
},
)
env_vars: Optional[Dict[str, StrPipeVar]] = field(
default_factory=dict,
metadata={
"help": "Environment variables to set in the model container at runtime. Used to pass "
"configuration and secrets to the inference code."
},
)
model_server: Optional[ModelServer] = field(
default=None,
metadata={
"help": "Model server to use for serving the model. Options include TORCHSERVE, MMS, "
"TENSORFLOW_SERVING, DJL_SERVING, TRITON, TGI, and TEI. Required when using a custom image_uri."
},
)
model_metadata: Optional[Dict[str, Any]] = field(
default=None,
metadata={
"help": "Dictionary to override model metadata. Supported keys: HF_TASK (for HuggingFace "
"models without task metadata), MLFLOW_MODEL_PATH (local or S3 path to MLflow artifacts), "
"FINE_TUNING_MODEL_PATH (S3 path to fine-tuned model), FINE_TUNING_JOB_NAME (fine-tuning "
"job name), and CUSTOM_MODEL_PATH (local or S3 path to custom model artifacts). "
"FINE_TUNING_MODEL_PATH and FINE_TUNING_JOB_NAME are mutually exclusive."
},
)
log_level: Optional[int] = field(
default=logging.DEBUG,
metadata={
"help": "Logging level for ModelBuilder operations. Valid values are logging.CRITICAL, "
"logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG, and logging.NOTSET. "
"Controls verbosity of ModelBuilder logs."
},
)
content_type: Optional[str] = field(
default=None,
metadata={
"help": "MIME type of the input data for inference requests (e.g., 'application/json', "
"'text/csv'). Automatically derived from the input sample if schema_builder is provided, "
"but can be overridden."
},
)
accept_type: Optional[str] = field(
default=None,
metadata={
"help": "MIME type of the output data from inference responses (e.g., 'application/json'). "
"Automatically derived from the output sample if schema_builder is provided, but can be overridden."
},
)
compute: Optional[Compute] = field(
default=None,
metadata={
"help": "Compute configuration specifying instance type and instance count for deployment. "
"Alternative to specifying instance_type separately."
},
)
network: Optional[Networking] = field(
default=None,
metadata={
"help": "Network configuration including VPC settings (subnets, security groups) and "
"network isolation settings for the model and endpoint."
},
)
instance_type: Optional[str] = field(
default=None,
metadata={
"help": "EC2 instance type for model deployment (e.g., 'ml.m5.large', 'ml.g5.xlarge'). "
"Used to determine appropriate container images and for deployment."
},
)
mode: Optional[Mode] = field(
default=Mode.SAGEMAKER_ENDPOINT,
metadata={
"help": "Deployment mode for the model. Options: Mode.SAGEMAKER_ENDPOINT (deploy to "
"SageMaker endpoint), Mode.LOCAL_CONTAINER (run locally in Docker container for testing), "
"Mode.IN_PROCESS (run locally in current Python process for testing)."
},
)
_base_name: Optional[str] = field(default=None, init=False)
_is_sharded_model: Optional[bool] = field(default=False, init=False)
_tags: Optional[Tags] = field(default=None, init=False)
_optimizing: bool = field(default=False, init=False)
_deployment_config: Optional[Dict[str, Any]] = field(default=None, init=False)
shared_libs: List[str] = field(
default_factory=list,
metadata={"help": "DEPRECATED: Use configure_for_torchserve() instead"},
)
dependencies: Optional[Dict[str, Any]] = field(
default_factory=lambda: {"auto": True},
metadata={"help": "DEPRECATED: Use configure_for_torchserve() instead"},
)
image_config: Optional[Dict[str, StrPipeVar]] = field(
default=None,
metadata={"help": "DEPRECATED: Use configure_for_torchserve() instead"},
)
def _create_session_with_region(self):
"""Create a SageMaker session with the correct region."""
if hasattr(self, "region") and self.region:
import boto3
boto_session = boto3.Session(region_name=self.region)
return Session(boto_session=boto_session)
return Session()
def __post_init__(self) -> None:
"""Initialize ModelBuilder after instantiation."""
import warnings
if self.sagemaker_session is None:
self.sagemaker_session = self._create_session_with_region()
# Set logger level based on log_level parameter
if self.log_level is not None:
logger.setLevel(self.log_level)
self._warn_about_deprecated_parameters(warnings)
self._initialize_compute_config()
self._initialize_network_config()
self._initialize_defaults()
self._initialize_jumpstart_config()
self._initialize_script_mode_variables()
def _warn_about_deprecated_parameters(self, warnings) -> None:
"""Issue deprecation warnings for legacy parameters."""
if self.shared_libs:
warnings.warn(
"The 'shared_libs' parameter is deprecated. Use configure_for_torchserve() instead.",
DeprecationWarning,
stacklevel=3,
)
if self.dependencies and self.dependencies != {"auto": False}:
warnings.warn(
"The 'dependencies' parameter is deprecated. Use configure_for_torchserve() instead.",
DeprecationWarning,
stacklevel=3,
)
if self.image_config is not None:
warnings.warn(
"The 'image_config' parameter is deprecated. Use configure_for_torchserve() instead.",
DeprecationWarning,
stacklevel=3,
)
def _initialize_compute_config(self) -> None:
"""Initialize compute configuration from Compute object."""
if self.compute:
self.instance_type = self.compute.instance_type
self.instance_count = self.compute.instance_count or 1
else:
if not hasattr(self, "instance_type") or self.instance_type is None:
self.instance_type = None
if not hasattr(self, "instance_count") or self.instance_count is None:
self.instance_count = 1
self._user_provided_instance_type = bool(self.compute and self.compute.instance_type)
if not self.instance_type:
self.instance_type = self._get_default_instance_type()
def _initialize_network_config(self) -> None:
"""Initialize network configuration from Networking object."""
if self.network:
if self.network.vpc_config:
self.vpc_config = self.network.vpc_config
else:
self.vpc_config = (
{
"Subnets": self.network.subnets or [],
"SecurityGroupIds": self.network.security_group_ids or [],
}
if (self.network.subnets or self.network.security_group_ids)
else None
)
self._enable_network_isolation = self.network.enable_network_isolation
else:
if not hasattr(self, "vpc_config"):
self.vpc_config = None
if not hasattr(self, "_enable_network_isolation"):
self._enable_network_isolation = False
def _initialize_defaults(self) -> None:
"""Initialize default values for unset parameters."""
if not hasattr(self, "model_name") or self.model_name is None:
self.model_name = "model-" + str(uuid.uuid4())[:8]
if not hasattr(self, "mode") or self.mode is None:
self.mode = Mode.SAGEMAKER_ENDPOINT
if not hasattr(self, "env_vars") or self.env_vars is None:
self.env_vars = {}
# Set region with priority: user input > sagemaker session > AWS account region > default
if not hasattr(self, "region") or not self.region:
if self.sagemaker_session and self.sagemaker_session.boto_region_name:
self.region = self.sagemaker_session.boto_region_name
else:
# Try to get region from boto3 session (AWS account config)
try:
import boto3
self.region = boto3.Session().region_name or None
except Exception:
self.region = None # Default fallback
# Set role_arn with priority: user input > execution role detection
if not self.role_arn:
self.role_arn = get_execution_role(self.sagemaker_session, use_default=True)
self._metadata_configs = None
self.s3_upload_path = None
self.container_config = "host"
self.inference_recommender_job_results = None
self.container_log_level = logging.INFO
if not hasattr(self, "framework"):
self.framework = None
if not hasattr(self, "framework_version"):
self.framework_version = None
def _fetch_default_instance_type_for_custom_model(self) -> str:
hosting_configs = self._fetch_hosting_configs_for_custom_model()
default_instance_type = hosting_configs.get("InstanceType")
if not default_instance_type:
raise ValueError(
"Model is not supported for deployment. "
"The hosting configuration does not specify a default instance type. "
"Please specify an instance_type explicitly or use a different model."
)
logger.info(f"Fetching Instance Type from Hosting Configs - {default_instance_type}")
return default_instance_type
def _resolve_model_artifact_uri(self) -> Optional[str]:
"""Resolve the correct model artifact URI based on deployment type.
This method determines the appropriate S3 URI for model artifacts depending on
whether we're deploying a base model, a fine-tuned adapter (LORA), or a fully
fine-tuned model.
Returns:
Optional[str]: S3 URI to model artifacts, or None when not needed
Logic:
- For LORA adapters: Returns None (adapter weights are separate)
- For fine-tuned models: Returns None (model data is handled by the recipe/container)
- For base models: Uses HostingArtifactUri from JumpStart hub metadata
- For non-model-customization: Returns None
Raises:
ValueError: If model package or hub metadata is unavailable when needed
"""
# Check if this is a LORA adapter deployment
peft_type = self._fetch_peft()
if peft_type == "LORA":
# LORA adapters don't need artifact_url - they reference base component
return None
# For model customization deployments, check if we have a model package
if self._is_model_customization():
model_package = self._fetch_model_package()
if model_package:
if (
hasattr(model_package, "inference_specification")
and model_package.inference_specification
and hasattr(model_package.inference_specification, "containers")
and model_package.inference_specification.containers
):
container = model_package.inference_specification.containers[0]
# For fine-tuned models (have model_data_source), return None.
# The model data is handled by the recipe/container configuration,
# not via artifact_url in CreateInferenceComponent.
if (
hasattr(container, "model_data_source")
and container.model_data_source
and hasattr(container.model_data_source, "s3_data_source")
and container.model_data_source.s3_data_source
):
return None
# For base models, get HostingArtifactUri from JumpStart
if hasattr(container, "base_model") and container.base_model:
try:
hub_document = self._fetch_hub_document_for_custom_model()
hosting_artifact_uri = hub_document.get("HostingArtifactUri")
if hosting_artifact_uri:
return hosting_artifact_uri
else:
logger.warning(
"HostingArtifactUri not found in JumpStart hub metadata. "
"Deployment may fail if artifact URI is required."
)
return None
except Exception as e:
logger.warning(
f"Failed to retrieve HostingArtifactUri from JumpStart metadata: {e}. "
f"Proceeding without artifact URI."
)
return None
# For non-model-customization deployments, return None
return None
def _infer_instance_type_from_jumpstart(self) -> str:
"""Infer the appropriate instance type from JumpStart model metadata.
Queries JumpStart metadata for the base model and selects an appropriate
instance type from the supported list. Prefers GPU instance types for
models that require GPU acceleration.
Returns:
str: The inferred instance type (e.g., 'ml.g5.12xlarge')
Raises:
ValueError: If instance type cannot be inferred from metadata
"""
try:
# Get the hub document which contains hosting configurations
hub_document = self._fetch_hub_document_for_custom_model()
hosting_configs = hub_document.get("HostingConfigs")
if not hosting_configs:
raise ValueError(
"Unable to infer instance type: Model does not have hosting configuration. "
"Please specify instance_type explicitly."
)
# Get the default hosting config
config = next(
(cfg for cfg in hosting_configs if cfg.get("Profile") == "Default"),
hosting_configs[0],
)
# Extract supported instance types
supported_instance_types = config.get("SupportedInstanceTypes", [])
default_instance_type = config.get("InstanceType") or config.get("DefaultInstanceType")
if not supported_instance_types and not default_instance_type:
raise ValueError(
"Unable to infer instance type: Model metadata does not specify "
"supported instance types. Please specify instance_type explicitly."
)
# If default instance type is specified, use it
if default_instance_type:
logger.info(
f"Inferred instance type from JumpStart metadata: {default_instance_type}"
)
return default_instance_type
# Fallback to first supported instance type
selected_type = supported_instance_types[0]
logger.info(f"Inferred instance type from JumpStart metadata: {selected_type}")
return selected_type
except Exception as e:
# Provide helpful error message with context
error_msg = (
f"Unable to infer instance type for model customization deployment: {str(e)}. "
"Please specify instance_type explicitly when creating ModelBuilder."
)
# Try to provide available instance types in error message if possible
try:
hub_document = self._fetch_hub_document_for_custom_model()
hosting_configs = hub_document.get("HostingConfigs", [])
if hosting_configs:
config = next(
(cfg for cfg in hosting_configs if cfg.get("Profile") == "Default"),
hosting_configs[0],
)
supported_types = config.get("SupportedInstanceTypes", [])
if supported_types:
error_msg += f"\nSupported instance types for this model: {supported_types}"
except Exception:
pass
raise ValueError(error_msg)
def _fetch_hub_document_for_custom_model(self) -> dict:
from sagemaker.core.shapes import BaseModel as CoreBaseModel
base_model: CoreBaseModel = (
self._fetch_model_package().inference_specification.containers[0].base_model
)
hub_content = HubContent.get(
hub_content_type="Model",
hub_name="SageMakerPublicHub",
hub_content_name=base_model.hub_content_name,
hub_content_version=base_model.hub_content_version,
)
return json.loads(hub_content.hub_content_document)
def _fetch_hosting_configs_for_custom_model(self) -> dict:
hosting_configs = self._fetch_hub_document_for_custom_model().get("HostingConfigs")
if not hosting_configs:
raise ValueError(
"Model is not supported for deployment. "
"The model does not have hosting configuration. "
"Please use a model that supports deployment or contact AWS support for assistance."
)
return hosting_configs
def _get_instance_resources(self, instance_type: str) -> tuple:
"""Get CPU and memory for an instance type by querying EC2."""
try:
ec2_client = self.sagemaker_session.boto_session.client("ec2")
ec2_instance_type = instance_type.replace("ml.", "")
response = ec2_client.describe_instance_types(InstanceTypes=[ec2_instance_type])
if response["InstanceTypes"]:
instance_info = response["InstanceTypes"][0]
cpus = instance_info["VCpuInfo"]["DefaultVCpus"]
memory_mb = instance_info["MemoryInfo"]["SizeInMiB"]
return cpus, memory_mb
except Exception as e:
logger.warning(
f"Could not query instance type {instance_type}: {e}. "
f"Unable to validate CPU requirements. Proceeding with recipe defaults."
)
return None, None
def _resolve_compute_requirements(
self, instance_type: str, user_resource_requirements: Optional[ResourceRequirements] = None
) -> InferenceComponentComputeResourceRequirements:
"""Resolve compute requirements by merging JumpStart metadata with user config.
Retrieves default compute requirements from JumpStart model metadata and merges
them with user-provided ResourceRequirements. User-provided values take precedence
over defaults. Automatically determines number_of_accelerator_devices_required for
GPU instances when not explicitly provided.
Args:
instance_type: The EC2 instance type for deployment (e.g., 'ml.g5.12xlarge')
user_resource_requirements: Optional user-provided resource requirements
Returns:
InferenceComponentComputeResourceRequirements with all fields populated
Raises:
ValueError: If requirements are incompatible with instance_type or if
accelerator count cannot be determined for GPU instances
Requirements: 2.1, 3.1, 3.2, 3.4
"""
# Start with defaults from JumpStart metadata
hub_document = self._fetch_hub_document_for_custom_model()
hosting_configs = hub_document.get("HostingConfigs", [])
if not hosting_configs:
raise ValueError(
"Unable to resolve compute requirements: Model does not have hosting configuration. "
"Please provide resource requirements explicitly."
)
# Get the default hosting config
config = next(
(cfg for cfg in hosting_configs if cfg.get("Profile") == "Default"), hosting_configs[0]
)
return self._resolve_compute_requirements_from_config(
instance_type=instance_type,
config=config,
user_resource_requirements=user_resource_requirements,
)
def _resolve_compute_requirements_from_config(
self,
instance_type: str,
config: dict,
user_resource_requirements: Optional[ResourceRequirements] = None,
) -> InferenceComponentComputeResourceRequirements:
"""Resolve compute requirements from a hosting config dictionary.
Helper method that extracts compute requirements from an already-fetched
hosting config and merges with user-provided requirements.
Args:
instance_type: The EC2 instance type for deployment
config: The hosting config dictionary from JumpStart metadata
user_resource_requirements: Optional user-provided resource requirements
Returns:
InferenceComponentComputeResourceRequirements with all fields populated
Raises:
ValueError: If requirements are incompatible with instance_type
"""
# Extract default compute requirements from metadata
compute_resource_requirements = config.get("ComputeResourceRequirements", {})
default_cpus = compute_resource_requirements.get("NumberOfCpuCoresRequired", 1)
# Use 1024 MB as safe default for min_memory - metadata values can exceed
# SageMaker inference component limits (which are lower than raw EC2 memory)
default_memory_mb = 1024
default_accelerators = compute_resource_requirements.get(
"NumberOfAcceleratorDevicesRequired"
)
# Get actual instance resources for validation
actual_cpus, actual_memory_mb = self._get_instance_resources(instance_type)
# Adjust CPU count if it exceeds instance capacity
if actual_cpus and default_cpus > actual_cpus:
logger.warning(
f"Default requirements request {default_cpus} CPUs but {instance_type} has {actual_cpus}. "
f"Adjusting to {actual_cpus}."
)
default_cpus = actual_cpus
# Initialize with defaults
final_cpus = default_cpus
final_min_memory = default_memory_mb
final_max_memory = None
final_accelerators = default_accelerators
# Merge with user-provided requirements (user values take precedence)
if user_resource_requirements:
if user_resource_requirements.num_cpus is not None:
final_cpus = user_resource_requirements.num_cpus
if user_resource_requirements.min_memory is not None:
final_min_memory = user_resource_requirements.min_memory
if user_resource_requirements.max_memory is not None:
final_max_memory = user_resource_requirements.max_memory
if user_resource_requirements.num_accelerators is not None:
final_accelerators = user_resource_requirements.num_accelerators
# Determine accelerator count for GPU instances if not provided
# Also strip accelerator count for CPU instances (AWS rejects it)
is_gpu_instance = self._is_gpu_instance(instance_type)
if not is_gpu_instance:
# CPU instance - must NOT include accelerator count
if final_accelerators is not None:
logger.info(
f"Removing accelerator count ({final_accelerators}) for CPU instance type {instance_type}"
)
final_accelerators = None
elif final_accelerators is None:
# GPU instance without accelerator count - try to infer
accelerator_count = self._infer_accelerator_count_from_instance_type(instance_type)
if accelerator_count is not None:
final_accelerators = accelerator_count
logger.info(
f"Inferred {final_accelerators} accelerator device(s) for instance type {instance_type}"
)
else:
# Cannot determine accelerator count - raise descriptive error
raise ValueError(
f"Instance type '{instance_type}' requires accelerator device count specification.\n"
f"Please provide ResourceRequirements with number of accelerators:\n\n"
f" from sagemaker.core.inference_config import ResourceRequirements\n\n"
f" resource_requirements = ResourceRequirements(\n"
f" requests={{\n"
f" 'num_accelerators': <number_of_gpus>,\n"
f" 'memory': {final_min_memory}\n"
f" }}\n"
f" )\n\n"
f"For {instance_type}, check AWS documentation for the number of GPUs available."
)
# Validate requirements are compatible with instance type
# Only validate user-provided requirements (defaults are already adjusted above)
if user_resource_requirements:
if (
actual_cpus
and user_resource_requirements.num_cpus is not None
and user_resource_requirements.num_cpus > actual_cpus
):
raise ValueError(
f"Resource requirements incompatible with instance type '{instance_type}'.\n"
f"Requested: {user_resource_requirements.num_cpus} CPUs\n"
f"Available: {actual_cpus} CPUs\n"
f"Please reduce CPU requirements or select a larger instance type."
)
if (
actual_memory_mb
and user_resource_requirements.min_memory is not None
and user_resource_requirements.min_memory > actual_memory_mb
):
raise ValueError(
f"Resource requirements incompatible with instance type '{instance_type}'.\n"
f"Requested: {user_resource_requirements.min_memory} MB memory\n"
f"Available: {actual_memory_mb} MB memory\n"
f"Please reduce memory requirements or select a larger instance type."
)
# Create and return InferenceComponentComputeResourceRequirements
requirements = InferenceComponentComputeResourceRequirements(
min_memory_required_in_mb=final_min_memory, number_of_cpu_cores_required=final_cpus
)
if final_max_memory is not None:
requirements.max_memory_required_in_mb = final_max_memory
if final_accelerators is not None:
requirements.number_of_accelerator_devices_required = final_accelerators
return requirements
def _infer_accelerator_count_from_instance_type(self, instance_type: str) -> Optional[int]:
"""Infer the number of accelerator devices by querying EC2 instance type info.
Args:
instance_type: The EC2 instance type (e.g., 'ml.g5.12xlarge')
Returns:
Number of accelerator devices, or None if cannot be determined
"""
try:
ec2_client = self.sagemaker_session.boto_session.client("ec2")
ec2_instance_type = instance_type.replace("ml.", "")
response = ec2_client.describe_instance_types(InstanceTypes=[ec2_instance_type])
if response["InstanceTypes"]:
gpu_info = response["InstanceTypes"][0].get("GpuInfo")
if gpu_info and gpu_info.get("Gpus"):
total_gpus = sum(g.get("Count", 0) for g in gpu_info["Gpus"])
if total_gpus > 0:
return total_gpus
except Exception as e:
logger.warning(f"Could not query GPU count for {instance_type}: {e}.")
return None
def _is_gpu_instance(self, instance_type: str) -> bool:
"""Check if an instance type has GPUs by querying EC2.
Args:
instance_type: The EC2 instance type (e.g., 'ml.g5.12xlarge')
Returns:
True if the instance type has GPUs, False otherwise
"""
gpu_count = self._infer_accelerator_count_from_instance_type(instance_type)
return gpu_count is not None and gpu_count > 0
def _fetch_and_cache_recipe_config(self):
"""Fetch and cache image URI, compute requirements, and s3_upload_path from recipe during build."""
hub_document = self._fetch_hub_document_for_custom_model()
model_package = self._fetch_model_package()
recipe_name = model_package.inference_specification.containers[0].base_model.recipe_name
if not self.s3_upload_path:
self.s3_upload_path = model_package.inference_specification.containers[
0
].model_data_source.s3_data_source.s3_uri
for recipe in hub_document.get("RecipeCollection", []):
if recipe.get("Name") == recipe_name:
hosting_configs = recipe.get("HostingConfigs", [])
if hosting_configs:
config = next(
(cfg for cfg in hosting_configs if cfg.get("Profile") == "Default"),
hosting_configs[0],
)
if not self.image_uri:
self.image_uri = config.get("EcrAddress")
# Cache environment variables from recipe config
if self.env_vars:
self.env_vars.update(config.get("Environment", {}))
else:
self.env_vars = config.get("Environment", {})
# Infer instance type from JumpStart metadata if not provided
# This is only called for model_customization deployments
if not self.instance_type:
# Try to get from recipe config first
self.instance_type = config.get("InstanceType") or config.get(
"DefaultInstanceType"
)
# If still not available, use the inference method
if not self.instance_type:
self.instance_type = self._infer_instance_type_from_jumpstart()
# Resolve compute requirements using the already-fetched hub document
# This ensures requirements are determined through public methods
# and properly merged with any user-provided configuration
self._cached_compute_requirements = (
self._resolve_compute_requirements_from_config(
instance_type=self.instance_type,
config=config,
user_resource_requirements=None, # No user config at build time
)
)
return
# Fallback: Nova recipes don't have hosting configs in the hub document
if self._is_nova_model():
nova_config = self._get_nova_hosting_config(instance_type=self.instance_type)
if not self.image_uri:
self.image_uri = nova_config["image_uri"]
if self.env_vars:
self.env_vars.update(nova_config["env_vars"])
else:
self.env_vars = nova_config["env_vars"]