5757 ModelCard ,
5858 ModelPackageModelCard ,
5959)
60- from sagemaker .core .utils .utils import logger
60+ from sagemaker .core .utils .utils import Unassigned , logger
6161from sagemaker .core .exceptions import CapacityError , UnexpectedStatusException
6262from sagemaker .core .helper import session_helper
6363from sagemaker .core .helper .iam_role_resolver import resolve_and_validate_role
@@ -261,6 +261,8 @@ class ModelBuilder(_InferenceRecommenderMixin, _ModelBuilderServers, _ModelBuild
261261 network: Network configuration including VPC settings and network isolation.
262262 instance_type: EC2 instance type for deployment (e.g., 'ml.m5.large').
263263 mode: Deployment mode (SAGEMAKER_ENDPOINT, LOCAL_CONTAINER, or IN_PROCESS).
264+ recipe_name: Optional recipe name used to select recipe-level hosting configuration when
265+ base model metadata omits it or the Hub document publishes multiple deployable recipes.
264266
265267 Note:
266268 ModelBuilder returns sagemaker.core.resources.Model and sagemaker.core.resources.Endpoint
@@ -450,6 +452,14 @@ class ModelBuilder(_InferenceRecommenderMixin, _ModelBuilderServers, _ModelBuild
450452 default = None ,
451453 metadata = {"help" : "DEPRECATED: Use configure_for_torchserve() instead" },
452454 )
455+ recipe_name : Optional [str ] = field (
456+ default = None ,
457+ metadata = {
458+ "help" : "Recipe name override for resolving recipe-level hosting configurations. "
459+ "Use this when base model metadata omits a recipe and the Hub document publishes "
460+ "multiple recipes with hosting configurations."
461+ },
462+ )
453463
454464 def _create_session_with_region (self ):
455465 """Create a SageMaker session with the correct region."""
@@ -750,22 +760,47 @@ def _infer_instance_type_from_jumpstart(self) -> str:
750760
751761 raise ValueError (error_msg )
752762
763+ @staticmethod
764+ def _optional_base_model_string (value : Any ) -> Optional [str ]:
765+ """Normalize an optional string from generated ``BaseModel`` metadata."""
766+ if value is None or isinstance (value , Unassigned ) or value == "" :
767+ return None
768+ return value
769+
770+ def _effective_recipe_name (self , base_model : Any ) -> Optional [str ]:
771+ """Return the public recipe override or the normalized BaseModel recipe."""
772+ return self ._optional_base_model_string (
773+ self .recipe_name
774+ ) or self ._optional_base_model_string (getattr (base_model , "recipe_name" , None ))
775+
753776 def _fetch_hub_document_for_custom_model (self ) -> dict :
754777 from sagemaker .core .shapes import BaseModel as CoreBaseModel
755778
756779 base_model : CoreBaseModel = (
757780 self ._fetch_model_package ().inference_specification .containers [0 ].base_model
758781 )
782+ hub_content_name = self ._optional_base_model_string (base_model .hub_content_name )
783+ if hub_content_name is None :
784+ raise ValueError (
785+ "Cannot resolve hosting configuration because the model package's BaseModel "
786+ "does not specify hub_content_name."
787+ )
788+ hub_content_version = self ._optional_base_model_string (base_model .hub_content_version )
789+
759790 # Prefer an explicitly configured hub (e.g. a private hub used for
760791 # testing or for sourcing pre-release hosting configs); fall back to the
761792 # public JumpStart hub when none is set.
762793 hub_name = getattr (self , "hub_name" , None ) or "SageMakerPublicHub"
763- hub_content = HubContent .get (
764- hub_content_type = "Model" ,
765- hub_name = hub_name ,
766- hub_content_name = base_model .hub_content_name ,
767- hub_content_version = base_model .hub_content_version ,
768- )
794+ get_kwargs = {
795+ "hub_content_type" : "Model" ,
796+ "hub_name" : hub_name ,
797+ "hub_content_name" : hub_content_name ,
798+ }
799+ # Omitting HubContentVersion asks SageMaker for the latest version. Passing
800+ # None, an empty string, or Unassigned would serialize an invalid request.
801+ if hub_content_version is not None :
802+ get_kwargs ["hub_content_version" ] = hub_content_version
803+ hub_content = HubContent .get (** get_kwargs )
769804 return json .loads (hub_content .hub_content_document )
770805
771806 def _fetch_hosting_configs_for_custom_model (self ) -> dict :
@@ -1011,28 +1046,41 @@ def _is_gpu_instance(self, instance_type: str) -> bool:
10111046
10121047 @staticmethod
10131048 def _extract_hosting_configs_from_hub (
1014- hub_document : Dict [str , Any ], recipe_name : str
1049+ hub_document : Dict [str , Any ], recipe_name : Optional [ str ]
10151050 ) -> List [Dict [str , Any ]]:
1016- """Discover the raw ``HostingConfigs`` for a recipe from an already-fetched hub document.
1017-
1018- The authoritative hosting configurations live under
1019- ``RecipeCollection[<recipe>].HostingConfigs``. Falls back to the top-level
1020- ``HostingConfigs`` when the matching recipe entry does not carry its own (some models
1021- publish there instead). Returns ``[]`` when neither is present — callers decide whether an
1022- empty result is an error (fine-tuned) or a signal to try another path (e.g. Nova).
1023-
1024- This is the single source of truth for config discovery so that
1025- :meth:`_resolve_recipe_hosting_configs` (used by list/get/set_deployment_config) and
1026- :meth:`_fetch_and_cache_recipe_config` (used by build) never diverge — in particular the
1027- top-level fallback is honored on BOTH the selection and the build paths.
1051+ """Discover raw ``HostingConfigs`` using explicit, top-level, or unique recipe metadata.
1052+
1053+ A named recipe is selected first and retains the historical top-level fallback. When no
1054+ recipe is available, top-level ``HostingConfigs`` takes precedence. Only if top-level
1055+ configs are absent does ModelBuilder infer a recipe, and only when exactly one recipe
1056+ publishes non-empty hosting configs.
10281057 """
1029- for recipe in hub_document .get ("RecipeCollection" , []):
1030- if recipe .get ("Name" ) == recipe_name :
1031- configs = recipe .get ("HostingConfigs" )
1032- if configs :
1033- return configs
1034- break
1035- return hub_document .get ("HostingConfigs" ) or []
1058+ recipe_name = ModelBuilder ._optional_base_model_string (recipe_name )
1059+ recipes = hub_document .get ("RecipeCollection" , []) or []
1060+ if recipe_name is not None :
1061+ for recipe in recipes :
1062+ if recipe .get ("Name" ) == recipe_name :
1063+ configs = recipe .get ("HostingConfigs" )
1064+ if configs :
1065+ return configs
1066+ break
1067+
1068+ top_level_configs = hub_document .get ("HostingConfigs" )
1069+ if top_level_configs :
1070+ return top_level_configs
1071+ if recipe_name is not None :
1072+ return []
1073+
1074+ candidates = [recipe for recipe in recipes if recipe .get ("HostingConfigs" )]
1075+ if len (candidates ) == 1 :
1076+ return candidates [0 ]["HostingConfigs" ]
1077+ if len (candidates ) > 1 :
1078+ candidate_names = [str (recipe .get ("Name" ) or "<unnamed>" ) for recipe in candidates ]
1079+ raise ValueError (
1080+ "Multiple recipes publish HostingConfigs: "
1081+ f"{ ', ' .join (candidate_names )} . Specify recipe_name when creating ModelBuilder."
1082+ )
1083+ return []
10361084
10371085 def _resolve_recipe_hosting_configs (self ) -> List [Dict [str , Any ]]:
10381086 """Return the raw ``HostingConfigs`` list published for this model's recipe.
@@ -1052,7 +1100,7 @@ def _resolve_recipe_hosting_configs(self) -> List[Dict[str, Any]]:
10521100 "Model is not supported for deployment: the model package has no inference "
10531101 "container to resolve a recipe from."
10541102 )
1055- recipe_name = getattr (containers [0 ].base_model , "recipe_name" , None ) or ""
1103+ recipe_name = self . _effective_recipe_name (containers [0 ].base_model )
10561104
10571105 configs = self ._extract_hosting_configs_from_hub (hub_document , recipe_name )
10581106 if configs :
@@ -1286,7 +1334,7 @@ def _fetch_and_cache_recipe_config(self):
12861334 hub_document = self ._fetch_hub_document_for_custom_model ()
12871335 model_package = self ._fetch_model_package ()
12881336 container = model_package .inference_specification .containers [0 ]
1289- recipe_name = getattr (container .base_model , "recipe_name" , None ) or ""
1337+ recipe_name = self . _effective_recipe_name (container .base_model )
12901338
12911339 if not self .s3_upload_path :
12921340 from sagemaker .serve .utils .model_package_utils import get_s3_uri_from_inference_spec
@@ -1546,7 +1594,11 @@ def _base_model_name(self) -> Optional[str]:
15461594 model_package = self ._fetch_model_package ()
15471595 if model_package is not None :
15481596 base_model = model_package .inference_specification .containers [0 ].base_model
1549- return getattr (base_model , "hub_content_name" , None ) if base_model else None
1597+ return (
1598+ self ._optional_base_model_string (getattr (base_model , "hub_content_name" , None ))
1599+ if base_model
1600+ else None
1601+ )
15501602 if isinstance (self .model , BaseTrainer ):
15511603 return self .model .base_model_name
15521604 # Raw S3 checkpoint: base model identity is supplied via model_metadata.
@@ -1572,8 +1624,13 @@ def _is_nova_model(self) -> bool:
15721624 if containers :
15731625 base_model = getattr (containers [0 ], "base_model" , None )
15741626 if base_model :
1575- recipe_name = getattr (base_model , "recipe_name" , None ) or ""
1576- hub_content_name = getattr (base_model , "hub_content_name" , None ) or ""
1627+ recipe_name = self ._effective_recipe_name (base_model ) or ""
1628+ hub_content_name = (
1629+ self ._optional_base_model_string (
1630+ getattr (base_model , "hub_content_name" , None )
1631+ )
1632+ or ""
1633+ )
15771634 if (isinstance (recipe_name , str ) and "nova" in recipe_name .lower ()) or (
15781635 isinstance (hub_content_name , str ) and "nova" in hub_content_name .lower ()
15791636 ):
@@ -1645,16 +1702,9 @@ def _get_nova_hosting_config_from_hub_document(self, instance_type=None):
16451702 return None
16461703
16471704 container = self ._fetch_model_package ().inference_specification .containers [0 ]
1648- recipe_name = getattr (container .base_model , "recipe_name" , None ) or ""
1649-
1650- hosting_configs = None
1651- for recipe in hub_document .get ("RecipeCollection" , []):
1652- if recipe .get ("Name" ) == recipe_name :
1653- hosting_configs = recipe .get ("HostingConfigs" )
1654- break
1655- if not hosting_configs :
1656- hosting_configs = hub_document .get ("HostingConfigs" )
1705+ recipe_name = self ._effective_recipe_name (container .base_model )
16571706
1707+ hosting_configs = self ._extract_hosting_configs_from_hub (hub_document , recipe_name )
16581708 if not hosting_configs :
16591709 return None
16601710
@@ -1690,9 +1740,9 @@ def _get_nova_hosting_config(self, instance_type=None):
16901740
16911741 model_package = self ._fetch_model_package ()
16921742 if model_package :
1693- hub_content_name = model_package . inference_specification . containers [
1694- 0
1695- ]. base_model . hub_content_name
1743+ hub_content_name = self . _optional_base_model_string (
1744+ model_package . inference_specification . containers [ 0 ]. base_model . hub_content_name
1745+ )
16961746 else :
16971747 # No model package (e.g. SMTJ trainer): resolve from base_model_name
16981748 base_model_name = self ._base_model_name ()
@@ -1747,7 +1797,9 @@ def _validate_nova_smi_config(self) -> None:
17471797 base_model = getattr (containers [0 ], "base_model" , None )
17481798 if not base_model :
17491799 return
1750- hub_content_name = getattr (base_model , "hub_content_name" , None )
1800+ hub_content_name = self ._optional_base_model_string (
1801+ getattr (base_model , "hub_content_name" , None )
1802+ )
17511803 if not hub_content_name :
17521804 return
17531805
@@ -3286,7 +3338,13 @@ def fetch_endpoint_names_for_base_model(self) -> Set[str]:
32863338 model_package = self ._fetch_model_package ()
32873339 if is_restricted_model_package (model_package ):
32883340 return set ()
3289- recipe_name = model_package .inference_specification .containers [0 ].base_model .recipe_name
3341+ base_model = model_package .inference_specification .containers [0 ].base_model
3342+ recipe_name = self ._effective_recipe_name (base_model )
3343+ if recipe_name is None :
3344+ raise ValueError (
3345+ "Cannot fetch endpoints for the base model because no recipe is available. "
3346+ "Specify recipe_name when creating ModelBuilder."
3347+ )
32903348 endpoint_names = set ()
32913349 logger .error (f"recipe_name: { recipe_name } " )
32923350 for inference_component in InferenceComponent .get_all ():
@@ -6465,8 +6523,8 @@ def _deploy_model_customization(
64656523 base_model_recipe_name = None
64666524 if peft_type == "LORA" :
64676525 container = model_package .inference_specification .containers [0 ]
6468- base_model_recipe_name = getattr (
6469- getattr (container , "base_model" , None ), "recipe_name" , None
6526+ base_model_recipe_name = self . _effective_recipe_name (
6527+ getattr (container , "base_model" , None )
64706528 )
64716529 if not base_model_recipe_name :
64726530 raise ValueError (
@@ -6681,7 +6739,7 @@ def _fetch_peft(self) -> Optional[str]:
66816739 if getattr (container , "is_checkpoint" , None ) is False :
66826740 return None
66836741 recipe_name = (
6684- getattr (getattr (container , "base_model" , None ), "recipe_name" , "" ) or ""
6742+ self . _effective_recipe_name (getattr (container , "base_model" , None )) or ""
66856743 )
66866744 if "lora" in recipe_name .lower ():
66876745 return "LORA"
@@ -6766,14 +6824,16 @@ def _deploy_nova_model(
67666824 # The jumpstart-model-id tag always applies (resolved from the model
67676825 # package or the trainer's base_model_name). The recipe-name tag is only
67686826 # available when a model package is present.
6769- tags = [
6770- {"key" : "sagemaker-sdk:jumpstart-model-id" , "value" : self ._base_model_name ()},
6771- ]
6827+ tags = []
6828+ base_model_name = self ._optional_base_model_string (self ._base_model_name ())
6829+ if base_model_name is not None :
6830+ tags .append ({"key" : "sagemaker-sdk:jumpstart-model-id" , "value" : base_model_name })
67726831 model_package = self ._fetch_model_package ()
67736832 if model_package is not None :
67746833 base_model = model_package .inference_specification .containers [0 ].base_model
6775- if base_model is not None and base_model .recipe_name :
6776- tags .append ({"key" : "sagemaker-sdk:recipe-name" , "value" : base_model .recipe_name })
6834+ recipe_name = self ._effective_recipe_name (base_model )
6835+ if recipe_name is not None :
6836+ tags .append ({"key" : "sagemaker-sdk:recipe-name" , "value" : recipe_name })
67776837
67786838 # Merge tags accumulated via add_tags (e.g. the model-source reuse tag).
67796839 # Those are stored in {"Key": ..., "Value": ...} form, so normalize to the
0 commit comments