forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_builder.py
More file actions
3950 lines (3401 loc) · 181 KB
/
model_builder.py
File metadata and controls
3950 lines (3401 loc) · 181 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,
)
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 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 _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 _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")
if not self.instance_type:
self.instance_type = config.get("InstanceType") or config.get("DefaultInstanceType")
compute_resource_requirements = config.get("ComputeResourceRequirements", {})
requested_cpus = compute_resource_requirements.get("NumberOfCpuCoresRequired", 1)
# Get actual CPU count from instance type
actual_cpus, _ = self._get_instance_resources(self.instance_type)
if actual_cpus and requested_cpus > actual_cpus:
logger.warning(
f"Recipe requests {requested_cpus} CPUs but {self.instance_type} has {actual_cpus}. "
f"Adjusting to {actual_cpus}."
)
requested_cpus = actual_cpus
self._cached_compute_requirements = InferenceComponentComputeResourceRequirements(
min_memory_required_in_mb=1024,
number_of_cpu_cores_required=requested_cpus
)
return
raise ValueError(
f"Model with recipe '{recipe_name}' is not supported for deployment. "
f"The recipe does not have hosting configuration. "
f"Please use a model that supports deployment or contact AWS support for assistance."
)
def _initialize_jumpstart_config(self) -> None:
"""Initialize JumpStart-specific configuration."""
if hasattr(self, "hub_name") and self.hub_name and not self.hub_arn:
from sagemaker.core.jumpstart.hub.utils import generate_hub_arn_for_init_kwargs
self.hub_arn = generate_hub_arn_for_init_kwargs(
hub_name=self.hub_name,
region=self.region,
session=self.sagemaker_session
)
else:
self.hub_name = None
self.hub_arn = None
if isinstance(self.model, str) and (not hasattr(self, "model_type") or not self.model_type):
from sagemaker.core.jumpstart.utils import validate_model_id_and_get_type
try:
self.model_type = validate_model_id_and_get_type(
model_id=self.model,
model_version=self.model_version or "*",
region=self.region,
hub_arn=self.hub_arn,
)
except Exception:
self.model_type = None
if isinstance(self.model, str) and self.model_type:
# Add tags for the JumpStart model
from sagemaker.core.jumpstart.utils import add_jumpstart_model_info_tags
from sagemaker.core.jumpstart.enums import JumpStartScriptScope
self._tags = add_jumpstart_model_info_tags(
self._tags,
self.model,
self.model_version or "*",
self.model_type,
self.config_name,
JumpStartScriptScope.INFERENCE,
)
if not hasattr(self, "tolerate_vulnerable_model"):
self.tolerate_vulnerable_model = None
if not hasattr(self, "tolerate_deprecated_model"):
self.tolerate_deprecated_model = None
if not hasattr(self, "model_data_download_timeout"):
self.model_data_download_timeout = None
if not hasattr(self, "container_startup_health_check_timeout"):
self.container_startup_health_check_timeout = None
if not hasattr(self, "inference_ami_version"):
self.inference_ami_version = None
if not hasattr(self, "model_version"):
self.model_version = None
if not hasattr(self, "resource_requirements"):
self.resource_requirements = None
if not hasattr(self, "model_kms_key"):
self.model_kms_key = None
if not hasattr(self, "hub_name"):
self.hub_name = None
if not hasattr(self, "config_name"):
self.config_name = None
if not hasattr(self, "accept_eula"):
self.accept_eula = None
def _initialize_script_mode_variables(self) -> None:
"""Initialize script mode variables from source_code or defaults."""
# Map SourceCode to model.py equivalents
if self.source_code:
self.entry_point = self.source_code.entry_script
if hasattr(self.source_code, 'requirements'):
self.script_dependencies = [self.source_code.requirements] if self.source_code.requirements else []
else:
self.script_dependencies = []
logger.warning(
"No requirements.txt file found in source_code. "
"If you have any dependencies, please add them to requirements.txt"
)
# source_dir already exists as field, but ensure consistency
if self.source_code.source_dir:
self.source_dir = self.source_code.source_dir
else:
self.source_dir = None
else:
self.entry_point = None
self.source_dir = None
# Initialize missing script mode variables
self.git_config = None
self.key_prefix = None
self.bucket = None
self.uploaded_code = None
self.repacked_model_data = None
def _get_client_translators(self) -> tuple:
"""Get serializer and deserializer for client-side data translation."""
serializer = None
deserializer = None
if self.content_type == "application/x-npy":
serializer = NumpySerializer()
elif self.content_type == "tensor/pt":
serializer = TorchTensorSerializer()
elif self.schema_builder and hasattr(self.schema_builder, "custom_input_translator"):
serializer = self.schema_builder.custom_input_translator
elif self.schema_builder:
serializer = self.schema_builder.input_serializer
if self.accept_type == "application/json":
deserializer = JSONDeserializer()
elif self.accept_type == "tensor/pt":
deserializer = TorchTensorDeserializer()
elif self.schema_builder and hasattr(self.schema_builder, "custom_output_translator"):
deserializer = self.schema_builder.custom_output_translator
elif self.schema_builder:
deserializer = self.schema_builder.output_deserializer
if serializer is None or deserializer is None:
auto_serializer, auto_deserializer = self._fetch_serializer_and_deserializer_for_framework(self.framework)
if serializer is None:
serializer = auto_serializer
if deserializer is None:
deserializer = auto_deserializer
if serializer is None:
raise ValueError("Cannot determine serializer. Try providing a SchemaBuilder.")
if deserializer is None:
raise ValueError("Cannot determine deserializer. Try providing a SchemaBuilder.")
return serializer, deserializer
def _save_model_inference_spec(self) -> None:
"""Save model or inference specification to the model path."""
# Skip saving for model customization - model artifacts already in S3
if self._is_model_customization():
return
if not os.path.exists(self.model_path):
os.makedirs(self.model_path)
code_path = Path(self.model_path).joinpath("code")
if self.inference_spec:
save_pkl(code_path, (self.inference_spec, self.schema_builder))
elif self.model:
if isinstance(self.model, str):
self.framework = None
self.env_vars.update({
"MODEL_CLASS_NAME": self.model
})
else:
fw, _ = _detect_framework_and_version(str(_get_model_base(self.model)))
self.framework = self._normalize_framework_to_enum(fw)
self.env_vars.update({
"MODEL_CLASS_NAME": f"{self.model.__class__.__module__}.{self.model.__class__.__name__}"
})
if self.framework == Framework.XGBOOST:
save_xgboost(code_path, self.model)
save_pkl(code_path, (self.framework, self.schema_builder))
else:
save_pkl(code_path, (self.model, self.schema_builder))
elif self._is_mlflow_model:
save_pkl(code_path, self.schema_builder)
else:
raise ValueError("Cannot detect required model or inference spec")
def _prepare_for_mode(
self, model_path: Optional[str] = None, should_upload_artifacts: Optional[bool] = False
) -> Optional[tuple]:
"""Prepare model artifacts for the specified deployment mode."""
self.s3_upload_path = None
if self.mode == Mode.SAGEMAKER_ENDPOINT:
self.modes[str(Mode.SAGEMAKER_ENDPOINT)] = SageMakerEndpointMode(
inference_spec=self.inference_spec, model_server=self.model_server
)
self.s3_upload_path, env_vars_sagemaker = self.modes[
str(Mode.SAGEMAKER_ENDPOINT)
].prepare(
(model_path or self.model_path),
self.secret_key,
self.serve_settings.s3_model_data_url,
self.sagemaker_session,
self.image_uri,
getattr(self, "model_hub", None) == ModelHub.JUMPSTART,
should_upload_artifacts=should_upload_artifacts,
)
env_vars_sagemaker = env_vars_sagemaker or {}
for key, value in env_vars_sagemaker.items():
self.env_vars.setdefault(key, value)
return self.s3_upload_path, env_vars_sagemaker
elif self.mode == Mode.LOCAL_CONTAINER:
self.modes[str(Mode.LOCAL_CONTAINER)] = LocalContainerMode(
inference_spec=self.inference_spec,
schema_builder=self.schema_builder,
session=self.sagemaker_session,
model_path=self.model_path,
env_vars=self.env_vars,
model_server=self.model_server,
)
self.modes[str(Mode.LOCAL_CONTAINER)].prepare()
if self.model_path:
self.s3_upload_path = f"file://{self.model_path}"
return None
elif self.mode == Mode.IN_PROCESS:
self.modes[str(Mode.IN_PROCESS)] = InProcessMode(
inference_spec=self.inference_spec,
model=self.model,
schema_builder=self.schema_builder,
session=self.sagemaker_session,
model_path=self.model_path,
env_vars=self.env_vars,
)
self.modes[str(Mode.IN_PROCESS)].prepare()
return None
raise ValueError(
f"Unsupported deployment mode: {self.mode}. "
f"Supported modes: {Mode.LOCAL_CONTAINER}, {Mode.SAGEMAKER_ENDPOINT}, {Mode.IN_PROCESS}"
)
def _build_validations(self) -> None:
"""Validate ModelBuilder configuration before building."""
if isinstance(self.model, ModelTrainer) and not self.inference_spec:
# Check if this is a JumpStart ModelTrainer (which doesn't need InferenceSpec)
if not (hasattr(self.model, '_jumpstart_config') and self.model._jumpstart_config is not None):
raise ValueError(
"InferenceSpec is required when using ModelTrainer, "
"unless it's a JumpStart ModelTrainer created with from_jumpstart_config()"
)
if isinstance(self.model, ModelTrainer):
is_jumpstart = hasattr(self.model, '_jumpstart_config') and self.model._jumpstart_config is not None
if not is_jumpstart and not self.image_uri:
logger.warning(
"Non-JumpStart ModelTrainer detected without image_uri. Consider providing image_uri "
"to skip auto-detection and improve build performance."
)
if is_jumpstart:
logger.info(
"JumpStart ModelTrainer detected. InferenceSpec and image_uri are optional "
"as JumpStart provides built-in inference logic and container detection."
)
else:
logger.info(
"Non-JumpStart ModelTrainer requires InferenceSpec and benefits from explicit image_uri "
"for optimal performance."
)
if self.inference_spec and self.model and not isinstance(self.model, ModelTrainer):
raise ValueError("Can only set one of the following: model, inference_spec.")
if self.image_uri and is_1p_image_uri(self.image_uri) and not self.model and not self.inference_spec and not getattr(self, '_is_mlflow_model', False):
self._passthrough = True
return
if self.image_uri and not is_1p_image_uri(self.image_uri) and not self.model and not self.inference_spec and not getattr(self, '_is_mlflow_model', False):
self._passthrough = True
return
self._passthrough = False
if self.image_uri and not is_1p_image_uri(self.image_uri) and self.model_server is None:
raise ValueError(
f"Model_server must be set when non-first-party image_uri is set. "
f"Supported model servers: {SUPPORTED_MODEL_SERVERS}"
)
def _build_for_passthrough(self) -> Model:
"""Build model for pass-through cases with image-only deployment."""
if not self.image_uri:
raise ValueError("image_uri is required for pass-through cases")
self.s3_upload_path = None
return self._create_model()
def _build_default_async_inference_config(self, async_inference_config):
"""Build default async inference config and return ``AsyncInferenceConfig``"""
unique_folder = unique_name_from_base(self.model_name)
if async_inference_config.output_path is None:
async_output_s3uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
"async-endpoint-outputs",
unique_folder,
)
async_inference_config.output_path = async_output_s3uri
if async_inference_config.failure_path is None:
async_failure_s3uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
"async-endpoint-failures",
unique_folder,
)
async_inference_config.failure_path = async_failure_s3uri
return async_inference_config
def enable_network_isolation(self):
"""Whether to enable network isolation when creating this Model
Returns:
bool: If network isolation should be enabled or not.
"""
return bool(self._enable_network_isolation)
def _is_model_customization(self) -> bool:
"""Check if the model is from a model customization/fine-tuning job.
Returns:
bool: True if the model is from model customization, False otherwise.
"""
from sagemaker.core.utils.utils import Unassigned
if not self.model:
return False
# Direct ModelPackage input
if isinstance(self.model, ModelPackage):
return True
# TrainingJob with model customization
# Check both model_package_config (new location) and serverless_job_config (legacy)
if isinstance(self.model, TrainingJob):
# Check model_package_config first (new location)
if (hasattr(self.model, 'model_package_config') and self.model.model_package_config != Unassigned
and getattr(self.model.model_package_config, 'source_model_package_arn', Unassigned) != Unassigned):
return True
# Fallback to serverless_job_config (legacy location)
if (hasattr(self.model, 'serverless_job_config') and self.model.serverless_job_config != Unassigned
and hasattr(self.model, 'output_model_package_arn') and self.model.output_model_package_arn!= Unassigned):
return True
# ModelTrainer with model customization
if isinstance(self.model, ModelTrainer) and hasattr(self.model, '_latest_training_job'):
# Check model_package_config first (new location)
if (hasattr(self.model._latest_training_job, 'model_package_config') and self.model._latest_training_job.model_package_config != Unassigned()
and getattr(self.model._latest_training_job.model_package_config, 'source_model_package_arn', Unassigned()) != Unassigned()):
return True
# Fallback to serverless_job_config (legacy location)
if (hasattr(self.model._latest_training_job, 'serverless_job_config') and self.model._latest_training_job.serverless_job_config != Unassigned()
and hasattr(self.model._latest_training_job, 'output_model_package_arn') and self.model._latest_training_job.output_model_package_arn!= Unassigned()):
return True
# BaseTrainer with model customization
if isinstance(self.model, BaseTrainer) and hasattr(self.model, '_latest_training_job'):
# Check model_package_config first (new location)
if (hasattr(self.model._latest_training_job, 'model_package_config') and self.model._latest_training_job.model_package_config != Unassigned()
and getattr(self.model._latest_training_job.model_package_config, 'source_model_package_arn', Unassigned()) != Unassigned()):
return True
# Fallback to serverless_job_config (legacy location)
if (hasattr(self.model._latest_training_job, 'serverless_job_config') and self.model._latest_training_job.serverless_job_config != Unassigned()
and hasattr(self.model._latest_training_job, 'output_model_package_arn') and self.model._latest_training_job.output_model_package_arn!= Unassigned()):
return True
return False
def _fetch_model_package_arn(self) -> Optional[str]:
"""Fetch the model package ARN from the model.
Returns:
Optional[str]: The model package ARN, or None if not available.
"""
from sagemaker.core.utils.utils import Unassigned
if isinstance(self.model, ModelPackage):
return self.model.model_package_arn
if isinstance(self.model, TrainingJob):
# Try output_model_package_arn first (preferred)
if hasattr(self.model, 'output_model_package_arn'):
arn = self.model.output_model_package_arn
if not isinstance(arn, Unassigned):
return arn
# Fallback to model_package_config.source_model_package_arn
if hasattr(self.model, 'model_package_config') and self.model.model_package_config != Unassigned and hasattr(self.model.model_package_config, 'source_model_package_arn'):
arn = self.model.model_package_config.source_model_package_arn
if not isinstance(arn, Unassigned):
return arn
# Fallback to serverless_job_config.source_model_package_arn (legacy)
if hasattr(self.model, 'serverless_job_config') and self.model.serverless_job_config != Unassigned and hasattr(self.model.serverless_job_config, 'source_model_package_arn'):
arn = self.model.serverless_job_config.source_model_package_arn
if not isinstance(arn, Unassigned):
return arn