Skip to content

Commit 1b90447

Browse files
committed
fix(core): keep environment variable names intact when parsing private hub model documents
Private hub model documents are converted between UpperCamelCase and snake_case several times while a JumpStartModelSpecs object is built. The hub document parser snake cases the instance type variants, the hub parsers turn the spec back into UpperCamelCase, and JumpStartModelSpecs snake cases it again, twice, when is_hub_content is set. walk_and_apply_json rewrote every key on every pass, including the environment variable names that are stored as keys under Variants.Properties.EnvironmentVariables, so SM_VLLM_MAX_MODEL_LEN came out as s_m__v_l_l_m__m_a_x__m_o_d_e_l__l_e_n and instance specific overrides never merged over the base defaults. The public hub path performs no key conversion, which is why the same model deploys correctly from the public catalog. walk_and_apply_json already has a stop list so that metric definitions are left alone, but it compared only the converted key, which meant a single list could not stop both conversion directions. Compare the original key as well and add environment_variables to the default stop list. The helper exists twice, in common_utils and in jumpstart.hub.parser_utils, and JumpStartInstanceTypeVariants uses the common_utils copy, so both copies receive the same change. Fixes #6191
1 parent 0e3e7c0 commit 1b90447

5 files changed

Lines changed: 273 additions & 4 deletions

File tree

‎sagemaker-core/src/sagemaker/core/common_utils.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2205,19 +2205,24 @@ def camel_to_snake(camel_case_string: str) -> str:
22052205

22062206

22072207
def walk_and_apply_json(
2208-
json_obj: Dict[Any, Any], apply, stop_keys: Optional[List[str]] = ["metrics"]
2208+
json_obj: Dict[Any, Any],
2209+
apply,
2210+
stop_keys: Optional[List[str]] = ["metrics", "environment_variables"],
22092211
) -> Dict[Any, Any]:
22102212
"""Recursively walks a json object and applies a given function to the keys.
22112213
22122214
stop_keys (Optional[list[str]]): List of field keys that should stop the application function.
22132215
Any children of these keys will not have the application function applied to them.
2216+
A key stops the walk if either its original or its converted form is in stop_keys, so
2217+
the same list works for camel_to_snake and snake_to_upper_camel passes. Environment
2218+
variable names are user facing values stored as keys and must never be converted.
22142219
"""
22152220

22162221
def _walk_and_apply_json(json_obj, new):
22172222
if isinstance(json_obj, dict) and isinstance(new, dict):
22182223
for key, value in json_obj.items():
22192224
new_key = apply(key)
2220-
if (stop_keys and new_key not in stop_keys) or stop_keys is None:
2225+
if stop_keys is None or (key not in stop_keys and new_key not in stop_keys):
22212226
if isinstance(value, dict):
22222227
new[new_key] = {}
22232228
_walk_and_apply_json(value, new=new[new_key])

‎sagemaker-core/src/sagemaker/core/jumpstart/hub/parser_utils.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,24 @@ def snake_to_upper_camel(snake_case_string: str) -> str:
3333

3434

3535
def walk_and_apply_json(
36-
json_obj: Dict[Any, Any], apply, stop_keys: Optional[List[str]] = ["metrics"]
36+
json_obj: Dict[Any, Any],
37+
apply,
38+
stop_keys: Optional[List[str]] = ["metrics", "environment_variables"],
3739
) -> Dict[Any, Any]:
3840
"""Recursively walks a json object and applies a given function to the keys.
3941
4042
stop_keys (Optional[list[str]]): List of field keys that should stop the application function.
4143
Any children of these keys will not have the application function applied to them.
44+
A key stops the walk if either its original or its converted form is in stop_keys, so
45+
the same list works for camel_to_snake and snake_to_upper_camel passes. Environment
46+
variable names are user facing values stored as keys and must never be converted.
4247
"""
4348

4449
def _walk_and_apply_json(json_obj, new):
4550
if isinstance(json_obj, dict) and isinstance(new, dict):
4651
for key, value in json_obj.items():
4752
new_key = apply(key)
48-
if (stop_keys and new_key not in stop_keys) or stop_keys is None:
53+
if stop_keys is None or (key not in stop_keys and new_key not in stop_keys):
4954
if isinstance(value, dict):
5055
new[new_key] = {}
5156
_walk_and_apply_json(value, new=new[new_key])
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License"). You
4+
# may not use this file except in compliance with the License. A copy of
5+
# the License is located at
6+
#
7+
# http://aws.amazon.com/apache2.0/
8+
#
9+
# or in the "license" file accompanying this file. This file is
10+
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11+
# ANY KIND, either express or implied. See the License for the specific
12+
# language governing permissions and limitations under the License.
13+
"""Unit tests for JumpStart environment variable retrieval."""
14+
from __future__ import absolute_import
15+
16+
import datetime
17+
import json
18+
import os
19+
from unittest.mock import patch
20+
21+
import pytest
22+
23+
from sagemaker.core.jumpstart.artifacts.environment_variables import (
24+
_retrieve_default_environment_variables,
25+
)
26+
from sagemaker.core.jumpstart.hub.interfaces import DescribeHubContentResponse
27+
from sagemaker.core.jumpstart.hub.parsers import (
28+
make_model_specs_from_describe_hub_content_response,
29+
)
30+
31+
HUB_ARN = "arn:aws:sagemaker:us-east-1:123456789012:hub/my-private-hub"
32+
33+
34+
@pytest.fixture
35+
def private_hub_model_specs():
36+
"""Model specs parsed from a private hub document, the way the JumpStart cache builds them."""
37+
path = os.path.join(os.path.dirname(__file__), "..", "hub_content_document.json")
38+
with open(path, "r") as f:
39+
hub_content_document = json.load(f)
40+
response = DescribeHubContentResponse(
41+
{
42+
"CreationTime": datetime.datetime(2024, 1, 1),
43+
"DocumentSchemaVersion": "2.0.0",
44+
"HubArn": HUB_ARN,
45+
"HubContentArn": (
46+
"arn:aws:sagemaker:us-east-1:123456789012:hub-content/"
47+
"my-private-hub/Model/meta-textgeneration-llama-2-13b-f/1.0.0"
48+
),
49+
"HubContentName": "meta-textgeneration-llama-2-13b-f",
50+
"HubContentType": "Model",
51+
"HubContentVersion": "1.0.0",
52+
"HubContentStatus": "Available",
53+
"HubName": "my-private-hub",
54+
"HubContentDocument": json.dumps(hub_content_document),
55+
}
56+
)
57+
return make_model_specs_from_describe_hub_content_response(response)
58+
59+
60+
@patch(
61+
"sagemaker.core.jumpstart.artifacts.environment_variables.verify_model_region_and_return_specs"
62+
)
63+
def test_private_hub_instance_specific_environment_variable_overrides_default(
64+
mock_verify_model_region_and_return_specs, private_hub_model_specs
65+
):
66+
"""An instance specific value must replace the model default rather than being added
67+
under a mangled second key, which is what ended up in the container environment before."""
68+
mock_verify_model_region_and_return_specs.return_value = private_hub_model_specs
69+
70+
environment_variables = _retrieve_default_environment_variables(
71+
model_id="meta-textgeneration-llama-2-13b-f",
72+
model_version="1.0.0",
73+
hub_arn=HUB_ARN,
74+
region="us-east-1",
75+
instance_type="ml.g5.48xlarge",
76+
sagemaker_session=None,
77+
)
78+
79+
gpu_keys = [key for key in environment_variables if key.replace("_", "").lower() == "smnumgpus"]
80+
assert gpu_keys == ["SM_NUM_GPUS"]
81+
assert environment_variables["SM_NUM_GPUS"] == "8"
82+
assert mock_verify_model_region_and_return_specs.call_args.kwargs["hub_arn"] == HUB_ARN
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License"). You
4+
# may not use this file except in compliance with the License. A copy of
5+
# the License is located at
6+
#
7+
# http://aws.amazon.com/apache2.0/
8+
#
9+
# or in the "license" file accompanying this file. This file is
10+
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11+
# ANY KIND, either express or implied. See the License for the specific
12+
# language governing permissions and limitations under the License.
13+
from __future__ import absolute_import
14+
15+
from sagemaker.core.jumpstart.hub.parser_utils import (
16+
camel_to_snake,
17+
snake_to_upper_camel,
18+
walk_and_apply_json,
19+
)
20+
21+
22+
VARIANTS = {
23+
"Variants": {
24+
"g5": {
25+
"Properties": {
26+
"ImageUri": "image",
27+
"EnvironmentVariables": {
28+
"SM_VLLM_MAX_MODEL_LEN": "131072",
29+
"HF_HUB_OFFLINE": "1",
30+
},
31+
"Metrics": [{"Name": "loss", "Regex": "loss=(.*)"}],
32+
}
33+
}
34+
}
35+
}
36+
37+
38+
def test_walk_and_apply_json_camel_to_snake_preserves_environment_variable_names():
39+
result = walk_and_apply_json(VARIANTS, camel_to_snake)
40+
41+
properties = result["variants"]["g5"]["properties"]
42+
assert properties["image_uri"] == "image"
43+
assert properties["environment_variables"] == {
44+
"SM_VLLM_MAX_MODEL_LEN": "131072",
45+
"HF_HUB_OFFLINE": "1",
46+
}
47+
assert properties["metrics"] == [{"Name": "loss", "Regex": "loss=(.*)"}]
48+
49+
50+
def test_walk_and_apply_json_snake_to_upper_camel_preserves_environment_variable_names():
51+
snake = walk_and_apply_json(VARIANTS, camel_to_snake)
52+
53+
result = walk_and_apply_json(snake, snake_to_upper_camel)
54+
55+
properties = result["Variants"]["G5"]["Properties"]
56+
assert properties["ImageUri"] == "image"
57+
assert properties["EnvironmentVariables"] == {
58+
"SM_VLLM_MAX_MODEL_LEN": "131072",
59+
"HF_HUB_OFFLINE": "1",
60+
}
61+
62+
63+
def test_walk_and_apply_json_round_trip_preserves_environment_variable_names():
64+
"""The private hub pipeline converts the same document several times in both directions."""
65+
result = walk_and_apply_json(VARIANTS, camel_to_snake)
66+
result = walk_and_apply_json(result, snake_to_upper_camel)
67+
result = walk_and_apply_json(result, camel_to_snake)
68+
result = walk_and_apply_json(result, camel_to_snake)
69+
70+
assert result["variants"]["g5"]["properties"]["environment_variables"] == {
71+
"SM_VLLM_MAX_MODEL_LEN": "131072",
72+
"HF_HUB_OFFLINE": "1",
73+
}
74+
75+
76+
def test_walk_and_apply_json_explicit_stop_keys_still_honored():
77+
result = walk_and_apply_json(
78+
{"Outer": {"Inner": {"KeepMe": 1}}}, camel_to_snake, stop_keys=["inner"]
79+
)
80+
81+
assert result == {"outer": {"inner": {"KeepMe": 1}}}
82+
83+
84+
def test_walk_and_apply_json_no_stop_keys_converts_everything():
85+
result = walk_and_apply_json(VARIANTS, camel_to_snake, stop_keys=None)
86+
87+
properties = result["variants"]["g5"]["properties"]
88+
assert "SM_VLLM_MAX_MODEL_LEN" not in properties["environment_variables"]
89+
assert properties["metrics"] == [{"name": "loss", "regex": "loss=(.*)"}]

‎sagemaker-core/tests/unit/jumpstart/hub/test_parsers.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
# ANY KIND, either express or implied. See the License for the specific
1212
# language governing permissions and limitations under the License.
1313

14+
import copy
15+
import datetime
16+
import json
17+
import os
1418
import pytest
1519
from unittest.mock import Mock, patch
1620
from sagemaker.core.jumpstart.hub.parsers import (
@@ -367,3 +371,87 @@ def test_make_model_specs_from_describe_hub_content_response_with_payloads(self)
367371
result = make_model_specs_from_describe_hub_content_response(response)
368372

369373
assert result is not None
374+
375+
def test_make_model_specs_preserves_instance_variant_environment_variable_names(
376+
self, hub_content_document
377+
):
378+
"""Environment variable names under HostingInstanceTypeVariants must survive verbatim."""
379+
variants = hub_content_document["InferenceConfigComponents"]["tgi"][
380+
"HostingInstanceTypeVariants"
381+
]["Variants"]
382+
variants["ml.g5.12xlarge"]["Properties"]["EnvironmentVariables"][
383+
"SM_VLLM_MAX_MODEL_LEN"
384+
] = "4096"
385+
variants["g5"]["Properties"]["EnvironmentVariables"] = {"HF_HUB_OFFLINE": "1"}
386+
387+
specs = make_model_specs_from_describe_hub_content_response(
388+
_describe_hub_content_response(hub_content_document)
389+
)
390+
391+
instance_type_variants = specs.hosting_instance_type_variants
392+
assert instance_type_variants.variants["ml.g5.12xlarge"]["properties"][
393+
"environment_variables"
394+
] == {"SM_NUM_GPUS": "4", "SM_VLLM_MAX_MODEL_LEN": "4096"}
395+
assert instance_type_variants.get_instance_specific_environment_variables(
396+
"ml.g5.12xlarge"
397+
) == {
398+
"HF_HUB_OFFLINE": "1",
399+
"SM_NUM_GPUS": "4",
400+
"SM_VLLM_MAX_MODEL_LEN": "4096",
401+
}
402+
403+
def test_make_model_specs_preserves_top_level_variant_environment_variable_names(
404+
self, hub_content_document
405+
):
406+
"""Top level HostingInstanceTypeVariants go through one more conversion pass than
407+
inference config components and must also keep environment variable names verbatim."""
408+
document = copy.deepcopy(hub_content_document)
409+
for key in ("InferenceConfigs", "InferenceConfigComponents", "InferenceConfigRankings"):
410+
document.pop(key, None)
411+
document["HostingInstanceTypeVariants"] = {
412+
"Variants": {
413+
"g5": {
414+
"Properties": {
415+
"ImageUri": "image",
416+
"EnvironmentVariables": {"SM_VLLM_MAX_MODEL_LEN": "131072"},
417+
}
418+
}
419+
}
420+
}
421+
422+
specs = make_model_specs_from_describe_hub_content_response(
423+
_describe_hub_content_response(document)
424+
)
425+
426+
instance_type_variants = specs.hosting_instance_type_variants
427+
assert instance_type_variants.variants["g5"]["properties"]["image_uri"] == "image"
428+
assert instance_type_variants.get_instance_specific_environment_variables(
429+
"ml.g5.12xlarge"
430+
) == {"SM_VLLM_MAX_MODEL_LEN": "131072"}
431+
432+
433+
def _describe_hub_content_response(hub_content_document):
434+
return DescribeHubContentResponse(
435+
{
436+
"CreationTime": datetime.datetime(2024, 1, 1),
437+
"DocumentSchemaVersion": "2.0.0",
438+
"HubArn": "arn:aws:sagemaker:us-east-1:123456789012:hub/my-private-hub",
439+
"HubContentArn": (
440+
"arn:aws:sagemaker:us-east-1:123456789012:hub-content/"
441+
"my-private-hub/Model/meta-textgeneration-llama-2-13b-f/1.0.0"
442+
),
443+
"HubContentName": "meta-textgeneration-llama-2-13b-f",
444+
"HubContentType": "Model",
445+
"HubContentVersion": "1.0.0",
446+
"HubContentStatus": "Available",
447+
"HubName": "my-private-hub",
448+
"HubContentDocument": json.dumps(hub_content_document),
449+
}
450+
)
451+
452+
453+
@pytest.fixture
454+
def hub_content_document():
455+
path = os.path.join(os.path.dirname(__file__), "..", "hub_content_document.json")
456+
with open(path, "r") as f:
457+
return json.load(f)

0 commit comments

Comments
 (0)