forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodel_builder_utils.py
More file actions
3514 lines (2931 loc) · 139 KB
/
model_builder_utils.py
File metadata and controls
3514 lines (2931 loc) · 139 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.
"""Utility functions and mixins for ModelBuilder.
This module provides utility functions for:
- Session management and initialization
- Instance type detection and optimization
- Container image auto-detection
- HuggingFace and JumpStart model handling
- Resource requirement calculation
- Framework serialization support
- MLflow model integration
- General model deployment utilities
Example:
Basic usage as a mixin class::
class MyModelBuilder(ModelBuilderUtils):
def __init__(self):
self.model = "huggingface-model-id"
self.instance_type = "ml.g5.xlarge"
def build(self):
self._auto_detect_image_uri()
return self.image_uri
"""
from __future__ import absolute_import, annotations
# Standard library imports
import importlib.util
import sys
import shutil
import json
import os
import platform
import re
import uuid
from pathlib import Path
import subprocess
from typing import Any, Dict, List, Optional, Tuple, Union
# Third-party imports
from packaging.version import Version
# SageMaker core imports
from sagemaker.core.helper.session_helper import Session
from sagemaker.core.utils.utils import logger
from sagemaker.train import ModelTrainer
# SageMaker serve imports
from sagemaker.serve.compute_resource_requirements import ResourceRequirements
from sagemaker.serve.constants import (
DEFAULT_SERIALIZERS_BY_FRAMEWORK,
Framework,
)
from sagemaker.serve.builder.schema_builder import SchemaBuilder
from sagemaker.serve.builder.serve_settings import _ServeSettings
from sagemaker.serve.detector.image_detector import (
_cast_to_compatible_version,
_detect_framework_and_version,
auto_detect_container,
_get_model_base,
)
from sagemaker.serve.mode.function_pointers import Mode
from sagemaker.serve.utils import task
from sagemaker.serve.utils.exceptions import TaskNotFoundException
from sagemaker.serve.utils.hardware_detector import _total_inference_model_size_mib
from sagemaker.serve.utils.types import ModelServer
from sagemaker.core.resources import Model
# MLflow imports
from sagemaker.core.shapes import (
InferenceComponentDataCacheConfig,
InferenceComponentContainerSpecification,
)
from sagemaker.serve.model_format.mlflow.constants import (
MLFLOW_METADATA_FILE,
MLFLOW_MODEL_PATH,
MLFLOW_PIP_DEPENDENCY_FILE,
MLFLOW_REGISTRY_PATH_REGEX,
MLFLOW_RUN_ID_REGEX,
MLFLOW_TRACKING_ARN,
MODEL_PACKAGE_ARN_REGEX,
)
from sagemaker.serve.model_format.mlflow.utils import (
_copy_directory_contents,
_download_s3_artifacts,
_generate_mlflow_artifact_path,
_get_all_flavor_metadata,
_get_default_model_server_for_mlflow,
_get_deployment_flavor,
_select_container_for_mlflow_model,
_validate_input_for_mlflow,
)
# SageMaker utils imports
from sagemaker.core.deserializers import JSONDeserializer
from sagemaker.core.jumpstart.accessors import JumpStartS3PayloadAccessor
from sagemaker.core.jumpstart.factory.utils import get_init_kwargs, get_deploy_kwargs
from sagemaker.core.jumpstart.utils import (
get_jumpstart_base_name_if_jumpstart_model,
get_jumpstart_content_bucket,
get_eula_message,
get_metrics_from_deployment_configs,
add_instance_rate_stats_to_benchmark_metrics,
)
from sagemaker.core.jumpstart.types import DeploymentConfigMetadata
from sagemaker.core.jumpstart import accessors
from sagemaker.core.enums import Tag
from sagemaker.core.local.local_session import LocalSession
from sagemaker.core.s3 import S3Downloader
from sagemaker.core.serializers import NumpySerializer
from sagemaker.core.common_utils import (
Tags,
_validate_new_tags,
base_name_from_image,
remove_tag_with_key,
)
from sagemaker.core.helper.pipeline_variable import PipelineVariable
from sagemaker.core import model_uris
from sagemaker.serve.utils.local_hardware import _get_available_gpus
from sagemaker.core.base_serializers import JSONSerializer
from sagemaker.core.deserializers import JSONDeserializer
from sagemaker.serve.detector.pickler import save_pkl
from sagemaker.serve.builder.requirements_manager import RequirementsManager
from sagemaker.serve.validations.check_integrity import (
compute_hash,
)
from sagemaker.core.remote_function.core.serialization import _MetaData
from sagemaker.serve.model_server.triton.config_template import CONFIG_TEMPLATE
SPECULATIVE_DRAFT_MODEL = "/opt/ml/additional-model-data-sources"
_DJL_MODEL_BUILDER_ENTRY_POINT = "inference.py"
_NO_JS_MODEL_EX = "HuggingFace JumpStart Model ID not detected. Building for HuggingFace Model ID."
_JS_SCOPE = "inference"
_CODE_FOLDER = "code"
_JS_MINIMUM_VERSION_IMAGE = "{}:0.31.0-lmi13.0.0-cu124"
_INVALID_DJL_SAMPLE_DATA_EX = (
'For djl-serving, sample input must be of {"inputs": str, "parameters": dict}, '
'sample output must be of [{"generated_text": str,}]'
)
_INVALID_TGI_SAMPLE_DATA_EX = (
'For tgi, sample input must be of {"inputs": str, "parameters": dict}, '
'sample output must be of [{"generated_text": str,}]'
)
SUPPORTED_TRITON_MODE = {Mode.LOCAL_CONTAINER, Mode.SAGEMAKER_ENDPOINT, Mode.IN_PROCESS}
SUPPORTED_TRITON_FRAMEWORK = {Framework.PYTORCH, Framework.TENSORFLOW}
INPUT_NAME = "input_1"
OUTPUT_NAME = "output_1"
TRITON_IMAGE_ACCOUNT_ID_MAP = {
"us-east-1": "785573368785",
"us-east-2": "007439368137",
"us-west-1": "710691900526",
"us-west-2": "301217895009",
"eu-west-1": "802834080501",
"eu-west-2": "205493899709",
"eu-west-3": "254080097072",
"eu-north-1": "601324751636",
"eu-south-1": "966458181534",
"eu-central-1": "746233611703",
"ap-east-1": "110948597952",
"ap-south-1": "763008648453",
"ap-northeast-1": "941853720454",
"ap-northeast-2": "151534178276",
"ap-southeast-1": "324986816169",
"ap-southeast-2": "355873309152",
"cn-northwest-1": "474822919863",
"cn-north-1": "472730292857",
"sa-east-1": "756306329178",
"ca-central-1": "464438896020",
"me-south-1": "836785723513",
"af-south-1": "774647643957",
}
GPU_INSTANCE_FAMILIES = {
"ml.g4dn",
"ml.g5",
"ml.p3",
"ml.p3dn",
"ml.p4",
"ml.p4d",
"ml.p4de",
"local_gpu",
}
TRITON_IMAGE_BASE = "{account_id}.dkr.ecr.{region}.{base}/sagemaker-tritonserver:{version}-py3"
LATEST_VERSION = "23.02"
VERSION_FOR_TF1 = "23.02"
class TritonSerializer(JSONSerializer):
"""A wrapper of JSONSerializer because Triton expects input to be certain format"""
def __init__(self, input_serializer, dtype: str, content_type="application/json"):
"""Initialize TritonSerializer with input serializer and data type."""
super().__init__(content_type)
self.input_serializer = input_serializer
self.dtype = dtype
def serialize(self, data):
"""Serialize data into Triton-compatible format."""
numpy_data = self.input_serializer.serialize(data)
payload = {
"inputs": [
{
"name": INPUT_NAME,
"shape": numpy_data.shape,
"datatype": self.dtype,
"data": numpy_data.tolist(),
}
]
}
return super().serialize(payload)
class _ModelBuilderUtils:
"""Utility mixin class providing common functionality for ModelBuilder.
This class provides utility methods for:
- Session management and initialization
- Instance type detection and optimization
- Container image auto-detection
- HuggingFace and JumpStart model handling
- Resource requirement calculation
- Framework serialization support
- MLflow model integration
- General model deployment utilities
This class is designed to be used as a mixin with ModelBuilder classes.
It expects certain attributes to be available on the instance:
- sagemaker_session: SageMaker session object
- model: Model identifier or object
- instance_type: EC2 instance type
- region: AWS region
- env_vars: Environment variables dict
Example:
class MyModelBuilder(ModelBuilderUtils):
def __init__(self):
self.model = "huggingface-model-id"
self.instance_type = "ml.g5.xlarge"
self.sagemaker_session = None
def build(self):
self._init_sagemaker_session_if_does_not_exist()
self._auto_detect_image_uri()
return self.image_uri
"""
# ========================================
# Session Management
# ========================================
def _init_sagemaker_session_if_does_not_exist(
self, instance_type: Optional[str] = None
) -> None:
"""Initialize SageMaker session if it doesn't exist.
Sets self.sagemaker_session to LocalSession for local instances,
or regular Session for remote instances.
Args:
instance_type: EC2 instance type to determine session type.
If None, uses self.instance_type.
"""
if self.sagemaker_session:
return
effective_instance_type = instance_type or getattr(self, "instance_type", None)
if effective_instance_type in ("local", "local_gpu"):
self.sagemaker_session = LocalSession(
sagemaker_config=getattr(self, "_sagemaker_config", None)
)
else:
# Create session with correct region
if hasattr(self, "region") and self.region:
import boto3
boto_session = boto3.Session(region_name=self.region)
self.sagemaker_session = Session(
boto_session=boto_session,
sagemaker_config=getattr(self, "_sagemaker_config", None),
)
else:
self.sagemaker_session = Session(
sagemaker_config=getattr(self, "_sagemaker_config", None)
)
# ========================================
# Instance Type Detection
# ========================================
def _get_jumpstart_recommended_instance_type(self) -> Optional[str]:
"""Get recommended instance type from JumpStart metadata.
Returns:
Recommended instance type string, or None if not available.
"""
try:
deploy_kwargs = get_deploy_kwargs(
model_id=self.model,
model_version=getattr(self, "model_version", None) or "*",
region=self.region,
tolerate_vulnerable_model=getattr(self, "tolerate_vulnerable_model", None),
tolerate_deprecated_model=getattr(self, "tolerate_deprecated_model", None),
)
# JumpStart provides recommended instance type
if hasattr(deploy_kwargs, "instance_type") and deploy_kwargs.instance_type:
return deploy_kwargs.instance_type
except Exception:
pass
return None
def _get_default_instance_type(self) -> str:
"""Get optimal default instance type based on model characteristics.
Analyzes the model to determine appropriate instance type:
- JumpStart models: Use recommended instance type from metadata
- HuggingFace models: Analyze model size and tags for GPU requirements
- Fallback: ml.m5.large for CPU workloads
Returns:
Instance type string (e.g., 'ml.g5.xlarge', 'ml.m5.large').
"""
logger.debug("Auto-detecting optimal instance type for model...")
if isinstance(self.model, str) and self._is_jumpstart_model_id():
recommended_type = self._get_jumpstart_recommended_instance_type()
if recommended_type:
logger.debug(f"Using JumpStart recommended instance type: {recommended_type}")
return recommended_type
# For HuggingFace models, use metadata to detect requirements
elif isinstance(self.model, str):
try:
env_vars = getattr(self, "env_vars", {}) or {}
hf_model_md = self.get_huggingface_model_metadata(
self.model, env_vars.get("HUGGING_FACE_HUB_TOKEN")
)
# Check model size from metadata
model_size = hf_model_md.get("safetensors", {}).get("total", 0)
model_tags = hf_model_md.get("tags", [])
# Large models or specific tags indicate GPU need
if (
model_size > 2_000_000_000 # > 2GB
or any(tag in model_tags for tag in ["7b", "13b", "70b"])
or "7b" in self.model.lower()
or "13b" in self.model.lower()
):
logger.debug("Detected large model, using GPU instance type: ml.g5.xlarge")
return "ml.g5.xlarge"
except Exception as e:
logger.debug(f"Could not get HF metadata for smart detection: {e}")
# Default fallback
logger.debug("Using default CPU instance type: ml.m5.large")
return "ml.m5.large"
# ========================================
# Image Detection and Container Utils
# ========================================
def _auto_detect_container_default(self) -> str:
"""Auto-detect container image for framework-based models.
Detects the appropriate Deep Learning Container (DLC) based on:
- Model framework (PyTorch, TensorFlow)
- Framework version from HuggingFace metadata
- Python version compatibility
- Instance type requirements
Returns:
Container image URI string.
Raises:
ValueError: If instance type not specified or no compatible image found.
"""
from sagemaker.core import image_uris
logger.debug("Auto-detecting image since image_uri was not provided in ModelBuilder()")
if not getattr(self, "instance_type", None):
raise ValueError(
"Instance type is not specified. "
"Unable to detect if the container needs to be GPU or CPU."
)
logger.warning(
"Auto detection is only supported for single models DLCs with a framework backend."
)
py_tuple = platform.python_version_tuple()
env_vars = getattr(self, "env_vars", {}) or {}
torch_v, tf_v, base_hf_v, _ = self._get_hf_framework_versions(
self.model, env_vars.get("HUGGING_FACE_HUB_TOKEN")
)
if torch_v:
fw, fw_version = "pytorch", torch_v
elif tf_v:
fw, fw_version = "tensorflow", tf_v
else:
raise ValueError("Could not detect framework from HuggingFace model metadata")
logger.debug("Auto-detected framework: %s", fw)
logger.debug("Auto-detected framework version: %s", fw_version)
casted_versions = _cast_to_compatible_version(fw, fw_version) if fw_version else (None,)
dlc = None
for casted_version in filter(None, casted_versions):
try:
dlc = image_uris.retrieve(
framework=fw,
region=self.region,
version=casted_version,
image_scope="inference",
py_version=f"py{py_tuple[0]}{py_tuple[1]}",
instance_type=self.instance_type,
)
break
except ValueError:
pass
if dlc:
logger.debug("Auto-detected container: %s. Proceeding with deployment.", dlc)
return dlc
raise ValueError(
f"Unable to auto-detect a DLC for framework {fw}, "
f"framework version {fw_version} and python version py{py_tuple[0]}{py_tuple[1]}. "
f"Please manually provide image_uri to ModelBuilder()"
)
def _get_smd_image_uri(self, processing_unit: Optional[str] = None) -> str:
"""Get SageMaker Distribution (SMD) inference image URI.
Retrieves the appropriate SMD container image for custom orchestrator deployment.
Requires Python >= 3.12 for SMD inference.
Args:
processing_unit: Target processing unit ('cpu' or 'gpu').
If None, defaults to 'cpu'.
Returns:
SMD inference image URI string.
Raises:
ValueError: If Python version < 3.12 or invalid processing unit.
"""
import sys
from sagemaker.core import image_uris
if not self.sagemaker_session:
if hasattr(self, "region") and self.region:
import boto3
boto_session = boto3.Session(region_name=self.region)
self.sagemaker_session = Session(boto_session=boto_session)
else:
self.sagemaker_session = Session()
formatted_py_version = f"py{sys.version_info.major}{sys.version_info.minor}"
if Version(f"{sys.version_info.major}{sys.version_info.minor}") < Version("3.12"):
raise ValueError(
f"Found Python version {formatted_py_version} but "
f"custom orchestrator deployment requires Python version >= 3.12."
)
INSTANCE_TYPES = {"cpu": "ml.c5.xlarge", "gpu": "ml.g5.4xlarge"}
effective_processing_unit = processing_unit or "cpu"
if effective_processing_unit not in INSTANCE_TYPES:
raise ValueError(
f"Invalid processing unit '{effective_processing_unit}'. "
f"Must be one of: {list(INSTANCE_TYPES.keys())}"
)
logger.debug(
"Finding SMD inference image URI for a %s instance.", effective_processing_unit
)
smd_uri = image_uris.retrieve(
framework="sagemaker-distribution",
image_scope="inference",
instance_type=INSTANCE_TYPES[effective_processing_unit],
region=self.region,
)
logger.debug("Found compatible image: %s", smd_uri)
return smd_uri
def _is_huggingface_model(self) -> bool:
"""Check if model is a HuggingFace model ID.
Determines if the model string represents a HuggingFace model by:
- Checking for organization/model-name format
- Checking explicit model_type designation
- Fallback: assume HuggingFace if not JumpStart
Returns:
True if model appears to be a HuggingFace model ID.
"""
if not isinstance(self.model, str):
return False
# Simple pattern matching for HuggingFace model IDs
# Format: "organization/model-name" or just "model-name"
model_type = getattr(self, "model_type", None)
if "/" in self.model or model_type == "huggingface":
return True
# Additional check: if it's not a JumpStart model, assume HuggingFace
return not self._is_jumpstart_model_id()
def _get_supported_version(
self, hf_config: Dict[str, Any], hugging_face_version: str, base_fw: str
) -> str:
"""Extract supported framework version from HuggingFace config.
Uses the HuggingFace JSON config to pick the best supported version
for the given framework.
Args:
hf_config: HuggingFace configuration dictionary
hugging_face_version: HuggingFace transformers version
base_fw: Base framework name (e.g., 'pytorch', 'tensorflow')
Returns:
Best supported framework version string.
"""
version_config = hf_config.get("versions", {}).get(hugging_face_version, {})
versions_to_return = []
for key in version_config.keys():
if key.startswith(base_fw):
base_fw_version = key[len(base_fw) :]
if len(hugging_face_version.split(".")) == 2:
base_fw_version = ".".join(base_fw_version.split(".")[:-1])
versions_to_return.append(base_fw_version)
if not versions_to_return:
raise ValueError(f"No supported versions found for framework {base_fw}")
return sorted(versions_to_return, reverse=True)[0]
def _get_hf_framework_versions(
self, model_id: str, hf_token: Optional[str] = None
) -> Tuple[Optional[str], Optional[str], str, str]:
"""Get HuggingFace framework versions for image_uris.retrieve().
Analyzes HuggingFace model metadata to determine the appropriate
framework versions for container image selection.
Args:
model_id: HuggingFace model identifier
hf_token: Optional HuggingFace API token for private models
Returns:
Tuple of (pytorch_version, tensorflow_version, transformers_version, py_version).
One of pytorch_version or tensorflow_version will be None.
Raises:
ValueError: If no supported framework versions found.
"""
from sagemaker.core import image_uris
# Get model metadata for framework detection
hf_model_md = self.get_huggingface_model_metadata(model_id, hf_token)
# Get HuggingFace framework configuration
hf_config = image_uris.config_for_framework("huggingface").get("inference")
config = hf_config["versions"]
base_hf_version = sorted(config.keys(), key=lambda v: Version(v), reverse=True)[0]
model_tags = hf_model_md.get("tags", [])
# Detect framework from model tags
if "pytorch" in model_tags:
pytorch_version = self._get_supported_version(hf_config, base_hf_version, "pytorch")
py_version = config[base_hf_version][f"pytorch{pytorch_version}"].get(
"py_versions", []
)[-1]
return pytorch_version, None, base_hf_version, py_version
elif "keras" in model_tags or "tensorflow" in model_tags:
tensorflow_version = self._get_supported_version(
hf_config, base_hf_version, "tensorflow"
)
py_version = config[base_hf_version][f"tensorflow{tensorflow_version}"].get(
"py_versions", []
)[-1]
return None, tensorflow_version, base_hf_version, py_version
else:
# Default to PyTorch if no framework detected (matches V2 behavior)
pytorch_version = self._get_supported_version(hf_config, base_hf_version, "pytorch")
py_version = config[base_hf_version][f"pytorch{pytorch_version}"].get(
"py_versions", []
)[-1]
return pytorch_version, None, base_hf_version, py_version
def _detect_jumpstart_image(self) -> None:
"""Detect and set image URI for JumpStart models.
Uses JumpStart metadata to determine the appropriate container image
and framework information for the model.
Raises:
ValueError: If image URI cannot be determined or JumpStart lookup fails.
"""
try:
init_kwargs = get_init_kwargs(
model_id=self.model,
model_version=getattr(self, "model_version", None) or "*",
region=self.region,
instance_type=getattr(self, "instance_type", None),
tolerate_vulnerable_model=getattr(self, "tolerate_vulnerable_model", None),
tolerate_deprecated_model=getattr(self, "tolerate_deprecated_model", None),
)
self.image_uri = init_kwargs.get("image_uri")
if not self.image_uri:
raise ValueError(f"Could not determine image URI for JumpStart model: {self.model}")
logger.debug("Auto-detected JumpStart image: %s", self.image_uri)
self.framework, self.framework_version = self._extract_framework_from_image_uri()
except Exception as e:
raise ValueError(
f"Failed to auto-detect image for JumpStart model {self.model}: {e}"
) from e
def _detect_huggingface_image(self) -> None:
"""Detect and set image URI for HuggingFace models based on model server.
Automatically selects the appropriate container image based on:
- Explicit model_server setting
- Model task type from HuggingFace metadata
- Framework requirements and versions
Raises:
ValueError: If image detection fails or unsupported model server.
"""
from sagemaker.core import image_uris
try:
env_vars = getattr(self, "env_vars", {}) or {}
# Determine which model server we're using
model_server = getattr(self, "model_server", None)
if not model_server:
# Auto-select model server based on HF model task
hf_model_md = self.get_huggingface_model_metadata(
self.model, env_vars.get("HUGGING_FACE_HUB_TOKEN")
)
model_task = hf_model_md.get("pipeline_tag")
if model_task == "text-generation":
effective_model_server = ModelServer.TGI
elif model_task in ["sentence-similarity", "feature-extraction"]:
effective_model_server = ModelServer.TEI
else:
effective_model_server = ModelServer.MMS # Transformers
else:
effective_model_server = model_server
# Choose image based on effective model server
if effective_model_server == ModelServer.TGI:
# TGI: Use image_uris.retrieve with "huggingface-llm" framework
self.image_uri = image_uris.retrieve(
"huggingface-llm",
region=self.region,
version=None, # Use latest version
image_scope="inference",
)
self.framework = Framework.HUGGINGFACE
elif effective_model_server == ModelServer.TEI:
# TEI: Use image_uris.retrieve with "huggingface-tei" framework
self.image_uri = image_uris.retrieve(
framework="huggingface-tei",
image_scope="inference",
instance_type=getattr(self, "instance_type", None),
region=self.region,
)
self.framework = Framework.HUGGINGFACE
elif effective_model_server == ModelServer.DJL_SERVING:
# DJL: Use image_uris.retrieve with "djl-lmi" framework (matches DJLModel default)
self.image_uri = image_uris.retrieve(
framework="djl-lmi",
region=self.region,
version="latest",
image_scope="inference",
instance_type=getattr(self, "instance_type", None),
)
self.framework = Framework.DJL
elif effective_model_server == ModelServer.MMS: # Transformers
# Transformers: Use HuggingFace framework with detected versions
pytorch_version, tensorflow_version, transformers_version, py_version = (
self._get_hf_framework_versions(
self.model, env_vars.get("HUGGING_FACE_HUB_TOKEN")
)
)
base_framework_version = (
f"pytorch{pytorch_version}"
if pytorch_version
else f"tensorflow{tensorflow_version}"
)
self.image_uri = image_uris.retrieve(
framework="huggingface",
region=self.region,
version=transformers_version,
py_version=py_version,
instance_type=getattr(self, "instance_type", None),
image_scope="inference",
base_framework_version=base_framework_version,
)
self.framework = Framework.HUGGINGFACE
elif effective_model_server == ModelServer.TORCHSERVE:
# TorchServe: Use HuggingFace framework with detected versions
pytorch_version, tensorflow_version, transformers_version, py_version = (
self._get_hf_framework_versions(
self.model, env_vars.get("HUGGING_FACE_HUB_TOKEN")
)
)
base_framework_version = (
f"pytorch{pytorch_version}"
if pytorch_version
else f"tensorflow{tensorflow_version}"
)
self.image_uri = image_uris.retrieve(
framework="huggingface",
region=self.region,
version=transformers_version,
py_version=py_version,
instance_type=getattr(self, "instance_type", None),
image_scope="inference",
base_framework_version=base_framework_version,
)
self.framework = Framework.HUGGINGFACE
elif effective_model_server == ModelServer.TRITON:
# Triton: Uses custom image construction (not image_uris.retrieve)
raise ValueError(
"Triton image detection for HuggingFace models requires custom implementation"
)
elif effective_model_server == ModelServer.TENSORFLOW_SERVING:
# TensorFlow Serving: V2 required explicit image_uri (no auto-detection)
raise ValueError("TensorFlow Serving requires explicit image_uri specification")
elif effective_model_server == ModelServer.SMD:
# SMD: Uses _get_smd_image_uri helper
cpu_or_gpu = self._get_processing_unit()
self.image_uri = self._get_smd_image_uri(processing_unit=cpu_or_gpu)
self.framework = Framework.SMD
else:
raise ValueError(
f"Unsupported model server for HuggingFace models: {effective_model_server}"
)
logger.debug("Auto-detected HuggingFace image: %s", self.image_uri)
except Exception as e:
raise ValueError(
f"Failed to auto-detect image for HuggingFace model {self.model}: {e}"
) from e
def _detect_model_object_image(self) -> None:
"""Detect image for legacy object-based models.
Handles model objects (not string IDs) by using the auto_detect_container
function to determine appropriate container image.
Raises:
ValueError: If neither model nor inference_spec available for detection.
"""
model = getattr(self, "model", None)
inference_spec = getattr(self, "inference_spec", None)
model_path = getattr(self, "model_path", None)
if model:
logger.debug(
"Auto-detecting container URL for the provided model on instance %s",
getattr(self, "instance_type", None),
)
self.image_uri, fw, self.framework_version = auto_detect_container(
model, self.region, getattr(self, "instance_type", None)
)
self.framework = self._normalize_framework_to_enum(fw)
elif inference_spec:
logger.warning(
"model_path provided with no image_uri. Attempting to auto-detect the image "
"by loading the model using inference_spec.load()..."
)
self.image_uri, fw, self.framework_version = auto_detect_container(
inference_spec.load(model_path),
self.region,
getattr(self, "instance_type", None),
)
self.framework = self._normalize_framework_to_enum(fw)
else:
raise ValueError("Cannot detect required model or inference spec")
def _auto_detect_image_uri(self) -> None:
"""Auto-detect container image URI based on model type.
Determines the appropriate container image by:
1. Using provided image_uri if available
2. For string models: JumpStart vs HuggingFace detection
3. For object models: Legacy auto-detection
Sets self.image_uri, self.framework, and self.framework_version.
Raises:
ValueError: If image cannot be auto-detected for the model type.
"""
image_uri = getattr(self, "image_uri", None)
if image_uri:
self.framework, self.framework_version = self._extract_framework_from_image_uri()
logger.debug("Skipping auto-detection as image_uri is provided: %s", image_uri)
return
if isinstance(self.model, ModelTrainer):
self._detect_inference_image_from_training()
return
model = getattr(self, "model", None)
inference_spec = getattr(self, "inference_spec", None)
if isinstance(model, str):
# V3: String-based model detection
model_type = getattr(self, "model_type", None)
# First priority: Use model_type if it indicates JumpStart
if model_type in ["open_weights", "proprietary"]:
self._detect_jumpstart_image()
else:
# model_type is None - use pattern-based detection
if self._is_jumpstart_model_id():
self._detect_jumpstart_image()
elif self._is_huggingface_model():
self._detect_huggingface_image()
else:
raise ValueError(f"Cannot auto-detect image for model: {model}")
elif inference_spec and hasattr(inference_spec, "get_model"):
try:
spec_model = inference_spec.get_model()
if spec_model is None:
logger.warning(
"InferenceSpec.get_model() returned None. If you are using a JumpStar or HuggingFace model, you may need to implement get_model() in your InferenceSpec class"
)
if isinstance(spec_model, str):
# Temporarily set model for detection, then restore
original_model = self.model
self.model = spec_model
# Use existing detection logic
if self._is_jumpstart_model_id():
self._detect_jumpstart_image()
elif self._is_huggingface_model():
self._detect_huggingface_image()
else:
raise ValueError(
f"Cannot auto-detect image for inference_spec model: {spec_model}"
)
# Restore original model
self.model = original_model
return
except Exception as e:
pass
# Fall back to existing object detection
self._detect_model_object_image()
else:
# V2: Object-based model detection
self._detect_model_object_image()
# ========================================
# HuggingFace Jumpstart Utils
# ========================================
def _use_jumpstart_equivalent(self) -> bool:
"""Check if HuggingFace model has JumpStart equivalent and use it.
Replaces the HuggingFace model with its JumpStart equivalent if available.
Skips replacement if image_uri or env_vars are explicitly provided.
Returns:
True if JumpStart equivalent was found and used, False otherwise.
"""
# Do not use the equivalent JS model if image_uri or env_vars is provided
image_uri = getattr(self, "image_uri", None)
env_vars = getattr(self, "env_vars", None)
if image_uri or env_vars:
return False
if not hasattr(self, "_has_jumpstart_equivalent"):
self._jumpstart_mapping = self._retrieve_hugging_face_model_mapping()
self._has_jumpstart_equivalent = self.model in self._jumpstart_mapping
if self._has_jumpstart_equivalent:
# Use schema builder from HF model metadata
schema_builder = getattr(self, "schema_builder", None)
if not schema_builder:
model_task = None
model_metadata = getattr(self, "model_metadata", None)
if model_metadata:
model_task = model_metadata.get("HF_TASK")
hf_model_md = self.get_huggingface_model_metadata(self.model)
if not model_task:
model_task = hf_model_md.get("pipeline_tag")
if model_task:
self._hf_schema_builder_init(model_task)
huggingface_model_id = self.model
jumpstart_model_id = self._jumpstart_mapping[huggingface_model_id]["jumpstart-model-id"]
self.model = jumpstart_model_id
merged_date = self._jumpstart_mapping[huggingface_model_id].get("merged-at")
# Call _build_for_jumpstart if method exists
if hasattr(self, "_build_for_jumpstart"):
self._build_for_jumpstart()
compare_model_diff_message = (
"If you want to identify the differences between the two, "
"please use model_uris.retrieve() to retrieve the model "
"artifact S3 URI and compare them."
)
is_gated = hasattr(self, "_is_gated_model") and self._is_gated_model()
logger.warning(
"Please note that for this model we are using the JumpStart's "
f'local copy "{jumpstart_model_id}" '
f'of the HuggingFace model "{huggingface_model_id}" you chose. '
"We strive to keep our local copy synced with the HF model hub closely. "
"This model was synced "
f"{f'on {merged_date}' if merged_date else 'before 11/04/2024'}. "
f"{compare_model_diff_message if not is_gated else ''}"
)
return True
return False
def _hf_schema_builder_init(self, model_task: str) -> None:
"""Initialize schema builder for HuggingFace model task.
Attempts to load I/O schemas locally first, then falls back to remote
schema retrieval for the given HuggingFace task.
Args:
model_task: HuggingFace task name (e.g., 'text-generation', 'text-classification')
Raises:
TaskNotFoundException: If I/O schema for the task cannot be found locally or remotely.
"""
try:
try:
sample_inputs, sample_outputs = task.retrieve_local_schemas(model_task)
except ValueError:
# Samples could not be loaded locally, try to fetch remote HF schema
from sagemaker_schema_inference_artifacts.huggingface import remote_schema_retriever
if model_task in ("text-to-image", "automatic-speech-recognition"):
logger.warning(