Skip to content

Commit 31956b7

Browse files
committed
fix(serve): pre-deploy JumpStart benchmark data + public HuggingFace download helper
Fixes ModelBuilder benchmark APIs for pre-deploy JumpStart models and adds a public HuggingFace-Hub download helper: - benchmark_metrics: display_benchmark_metrics() read self.benchmark_metrics, a property that existed in v2 but was dropped in the v3 port, so it raised AttributeError. Restore the property (a pandas DataFrame built from the model's published deployment-config benchmark data). - list_deployment_configs(): with no instance_type it called _get_deployment_configs() before the JumpStart metadata configs were loaded, so a pre-deploy builder (_metadata_configs=None) got []. _get_deployment_configs now calls _ensure_metadata_configs() itself, so every caller lazily loads them. - ragged benchmark data: get_metrics_from_deployment_configs built columns independently, appending the instance-rate (pricing) column only for instances that had it. That produced unequal-length columns (crashing pd.DataFrame with "All arrays must be of the same length") AND misaligned the present rate values onto the wrong rows. Assemble one record per row and pivot to columns at the end, padding unset cells with None, so columns stay equal length and every value stays on its own row. Column layout is unchanged (the rate column still comes last). - download_huggingface_model(): new public helper in serve.utils.hf_utils, exported from sagemaker.serve. Downloads a Hub snapshot and optionally uploads it to S3, so notebooks no longer hand-roll snapshot_download + S3Uploader. Supports revision / allow_patterns / ignore_patterns passthroughs; when staging to S3 without a caller-supplied local_dir it uses a temporary directory that is removed after the upload. migration.md documents both new surfaces. Unit: 11 new tests (benchmark/config, ragged-metrics alignment/order, HF helper incl. temp-dir cleanup and passthroughs).
1 parent d768dce commit 31956b7

9 files changed

Lines changed: 373 additions & 16 deletions

File tree

‎migration.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,8 @@ pipeline = Pipeline(
441441
| Predictor | Endpoint | Replaced with sagemaker-core |
442442
| MultiDataModel | ModelBuilder | Multi-model endpoints |
443443
| AsyncPredictor | ModelBuilder | Async inference |
444+
| JumpStartModel.benchmark_metrics / display_benchmark_metrics() / list_deployment_configs() | ModelBuilder.benchmark_metrics / display_benchmark_metrics() / list_deployment_configs() | Same names; usable on a pre-deploy JumpStart `ModelBuilder` |
445+
| snapshot_download + S3Uploader (hand-rolled) | `from sagemaker.serve import download_huggingface_model` | Downloads a Hub snapshot and optionally uploads it to S3 |
444446

445447
### Processing Features
446448

‎sagemaker-core/src/sagemaker/core/jumpstart/utils.py‎

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1442,8 +1442,19 @@ def get_metrics_from_deployment_configs(
14421442
if not deployment_configs:
14431443
return {}
14441444

1445-
data = {"Instance Type": [], "Config Name": [], "Concurrent Users": []}
1446-
instance_rate_data = {}
1445+
# Build per-row records, then pivot to column-oriented at the end, padding
1446+
# columns a row didn't set with None. Keeps every column the same length and
1447+
# each value on its own row; appending columns independently would crash
1448+
# pd.DataFrame on ragged lengths and misalign the sparse (pricing) column.
1449+
rows: List[Dict[str, Any]] = []
1450+
column_order: List[str] = ["Instance Type", "Config Name", "Concurrent Users"]
1451+
seen_columns = set(column_order)
1452+
1453+
def _register_column(name: str) -> None:
1454+
if name not in seen_columns:
1455+
seen_columns.add(name)
1456+
column_order.append(name)
1457+
14471458
for index, deployment_config in enumerate(deployment_configs):
14481459
benchmark_metrics = deployment_config.benchmark_metrics
14491460
if not deployment_config.deployment_args or not benchmark_metrics:
@@ -1465,25 +1476,31 @@ def get_metrics_from_deployment_configs(
14651476
else current_instance_type
14661477
)
14671478

1468-
data["Config Name"].append(deployment_config.deployment_config_name)
1469-
data["Instance Type"].append(instance_type_to_display)
1470-
data["Concurrent Users"].append(concurrent_user)
1479+
row: Dict[str, Any] = {
1480+
"Instance Type": instance_type_to_display,
1481+
"Config Name": deployment_config.deployment_config_name,
1482+
"Concurrent Users": concurrent_user,
1483+
}
1484+
1485+
for metric in metrics:
1486+
column_name = _normalize_benchmark_metric_column_name(metric.name, metric.unit)
1487+
_register_column(column_name)
1488+
row[column_name] = metric.value
14711489

14721490
if instance_type_rate:
14731491
instance_rate_column_name = (
14741492
f"{instance_type_rate.name} ({instance_type_rate.unit})"
14751493
)
1476-
instance_rate_data[instance_rate_column_name] = instance_rate_data.get(
1477-
instance_rate_column_name, []
1478-
)
1479-
instance_rate_data[instance_rate_column_name].append(instance_type_rate.value)
1494+
_register_column(instance_rate_column_name)
1495+
row[instance_rate_column_name] = instance_type_rate.value
14801496

1481-
for metric in metrics:
1482-
column_name = _normalize_benchmark_metric_column_name(metric.name, metric.unit)
1483-
data[column_name] = data.get(column_name, [])
1484-
data[column_name].append(metric.value)
1497+
rows.append(row)
14851498

1486-
data = {**data, **instance_rate_data}
1499+
# Pivot to column-oriented, padding unset cells with None.
1500+
data: Dict[str, List[Any]] = {column: [] for column in column_order}
1501+
for row in rows:
1502+
for column in column_order:
1503+
data[column].append(row.get(column))
14871504
return data
14881505

14891506

‎sagemaker-core/tests/unit/test_jumpstart_utils.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,53 @@ def test_get_metrics_from_deployment_configs_with_metrics(self):
16791679
assert "Instance Type" in result
16801680
assert "Config Name" in result
16811681

1682+
def test_get_metrics_ragged_pricing_stays_equal_length_and_aligned(self):
1683+
"""One instance with a pricing overlay, one without: columns stay equal
1684+
length and the rate stays aligned to its instance (None for the other)."""
1685+
1686+
def _stat(name, unit, value, concurrency):
1687+
stat = Mock()
1688+
stat.name = name
1689+
stat.unit = unit
1690+
stat.value = value
1691+
stat.concurrency = concurrency
1692+
return stat
1693+
1694+
mock_args = Mock()
1695+
mock_args.default_instance_type = "ml.g5.xlarge"
1696+
mock_args.instance_type = "ml.g5.xlarge"
1697+
1698+
mock_config = Mock(spec=DeploymentConfigMetadata)
1699+
mock_config.deployment_args = mock_args
1700+
mock_config.deployment_config_name = "config1"
1701+
# priced instance carries an "Instance Rate" stat; the other does not.
1702+
mock_config.benchmark_metrics = {
1703+
"ml.g5.xlarge": [
1704+
_stat("Latency", "ms", 100, "1"),
1705+
_stat("Instance Rate", "USD/Hr", 1.23, "1"),
1706+
],
1707+
"ml.g5.2xlarge": [
1708+
_stat("Latency", "ms", 90, "1"),
1709+
],
1710+
}
1711+
1712+
result = utils.get_metrics_from_deployment_configs([mock_config])
1713+
1714+
# Equal-length columns -> pd.DataFrame(result) will not raise.
1715+
lengths = {column: len(values) for column, values in result.items()}
1716+
assert len(set(lengths.values())) == 1, lengths
1717+
1718+
# Rate value stays on the priced row, None on the other (not shifted).
1719+
rate_cols = [c for c in result if "Instance Rate" in c]
1720+
assert rate_cols, result.keys()
1721+
rate_col = rate_cols[0]
1722+
by_instance = dict(zip(result["Instance Type"], result[rate_col]))
1723+
assert by_instance["ml.g5.xlarge (Default)"] == 1.23
1724+
assert by_instance["ml.g5.2xlarge"] is None
1725+
1726+
# Rate column stays last, after the metric columns (layout unchanged).
1727+
assert list(result).index(rate_col) == len(result) - 1
1728+
16821729

16831730
class TestNormalizeBenchmarkMetricColumnName:
16841731
"""Test cases for _normalize_benchmark_metric_column_name function"""

‎sagemaker-serve/src/sagemaker/serve/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
WorkloadValidationError,
4242
start_benchmark,
4343
)
44+
from sagemaker.serve.utils.hf_utils import download_huggingface_model
4445

4546
__all__ = [
4647
"InferenceSpec",
@@ -56,4 +57,5 @@
5657
"FeatureGatedError",
5758
"WorkloadValidationError",
5859
"start_benchmark",
60+
"download_huggingface_model",
5961
]

‎sagemaker-serve/src/sagemaker/serve/model_builder.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4782,6 +4782,20 @@ def transformer(
47824782
sagemaker_session=self.sagemaker_session,
47834783
)
47844784

4785+
@property
4786+
def benchmark_metrics(self):
4787+
"""Benchmark metrics for the model's JumpStart deployment configs.
4788+
4789+
Returns a pandas ``DataFrame`` (one row per config/instance) built from
4790+
the model's published benchmark data. Available for JumpStart models
4791+
(or HuggingFace models with a JumpStart equivalent) before deploy.
4792+
"""
4793+
import pandas as pd
4794+
4795+
df = pd.DataFrame(self._get_deployment_configs_benchmarks_data())
4796+
df.index = [""] * len(df)
4797+
return df
4798+
47854799
@_telemetry_emitter(
47864800
feature=Feature.MODEL_CUSTOMIZATION, func_name="model_builder.display_benchmark_metrics"
47874801
)

‎sagemaker-serve/src/sagemaker/serve/model_builder_utils.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2709,6 +2709,11 @@ def _get_deployment_configs(
27092709
selected_config_name (Optional[str]): The name of the selected deployment config.
27102710
selected_instance_type (Optional[str]): The selected instance type.
27112711
"""
2712+
# Lazily load the JumpStart metadata configs. Without this a pre-deploy
2713+
# builder (model set, build()/deploy() not yet called) has
2714+
# _metadata_configs=None, so both list_deployment_configs() and the
2715+
# benchmark-metrics data would come back empty.
2716+
self._ensure_metadata_configs()
27122717
deployment_configs = []
27132718
if not self._metadata_configs:
27142719
return deployment_configs

‎sagemaker-serve/src/sagemaker/serve/utils/hf_utils.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,108 @@
1414

1515
from __future__ import absolute_import
1616
import json
17+
import os
18+
import tempfile
1719
import urllib.request
1820
from json import JSONDecodeError
21+
from typing import Optional
1922
from urllib.error import HTTPError, URLError
2023
import logging
2124

2225
logger = logging.getLogger(__name__)
2326

2427

28+
def download_huggingface_model(
29+
model_id: str,
30+
*,
31+
local_dir: Optional[str] = None,
32+
s3_uri: Optional[str] = None,
33+
hf_hub_token: Optional[str] = None,
34+
revision: Optional[str] = None,
35+
allow_patterns=None,
36+
ignore_patterns=None,
37+
sagemaker_session=None,
38+
) -> str:
39+
"""Download a HuggingFace Hub model snapshot, optionally staging it to S3.
40+
41+
A supported, importable helper so notebooks and scripts don't hand-roll
42+
``huggingface_hub.snapshot_download`` + ``S3Uploader``. Downloads the full
43+
model snapshot from the Hub, then either leaves it on local disk or uploads
44+
it to S3 and returns the resulting location.
45+
46+
Args:
47+
model_id: The HuggingFace Hub model id (e.g. ``"gpt2"``).
48+
local_dir: Local directory to download into. When ``s3_uri`` is given
49+
and ``local_dir`` is omitted, the snapshot is downloaded into a
50+
temporary directory that is removed after the upload. Defaults to
51+
``None``.
52+
s3_uri: Optional ``s3://bucket/prefix`` destination. When set, the
53+
snapshot is uploaded there and the returned value is the S3 URI.
54+
hf_hub_token: Optional HuggingFace Hub token for gated/private models.
55+
revision: Optional Hub revision (branch, tag, or commit) to pin; passed
56+
through to ``snapshot_download``. Defaults to the repo's default
57+
branch.
58+
allow_patterns: Optional glob(s) of files to include, passed through to
59+
``snapshot_download`` (e.g. ``"*.safetensors"`` to skip duplicate
60+
``.bin`` weights).
61+
ignore_patterns: Optional glob(s) of files to exclude, passed through to
62+
``snapshot_download``.
63+
sagemaker_session: Optional session used for the S3 upload. Defaults to
64+
a new session built from the ambient AWS configuration.
65+
66+
Returns:
67+
The S3 URI the snapshot was uploaded to when ``s3_uri`` is given,
68+
otherwise the local directory path the snapshot was downloaded into.
69+
70+
Raises:
71+
ImportError: If ``huggingface_hub`` is not installed.
72+
ValueError: If neither ``local_dir`` nor ``s3_uri`` is given.
73+
"""
74+
if local_dir is None and s3_uri is None:
75+
raise ValueError("Provide local_dir, s3_uri, or both.")
76+
77+
try:
78+
from huggingface_hub import snapshot_download
79+
except ImportError as exc:
80+
raise ImportError(
81+
"download_huggingface_model requires huggingface_hub, which is not "
82+
"installed. Install it with `pip install huggingface_hub`."
83+
) from exc
84+
85+
def _download(target: str) -> None:
86+
os.makedirs(target, exist_ok=True)
87+
logger.info("Downloading model %s from Hugging Face Hub to %s", model_id, target)
88+
snapshot_download(
89+
repo_id=model_id,
90+
local_dir=target,
91+
token=hf_hub_token,
92+
revision=revision,
93+
allow_patterns=allow_patterns,
94+
ignore_patterns=ignore_patterns,
95+
)
96+
97+
if s3_uri is None:
98+
_download(local_dir)
99+
return local_dir
100+
101+
from sagemaker.core.s3 import S3Uploader
102+
103+
def _upload(source: str) -> str:
104+
logger.info("Uploading model %s snapshot to %s", model_id, s3_uri)
105+
return S3Uploader.upload(
106+
local_path=source,
107+
desired_s3_uri=s3_uri,
108+
sagemaker_session=sagemaker_session,
109+
)
110+
111+
if local_dir is not None:
112+
_download(local_dir)
113+
return _upload(local_dir)
114+
with tempfile.TemporaryDirectory(prefix="hf-model-") as staging_dir:
115+
_download(staging_dir)
116+
return _upload(staging_dir)
117+
118+
25119
def _get_model_config_properties_from_hf(model_id: str, hf_hub_token: str = None):
26120
"""Placeholder docstring"""
27121

‎sagemaker-serve/tests/unit/test_model_builder_coverage_boost.py‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"""
55

66
import unittest
7-
from unittest.mock import Mock, patch, MagicMock
7+
from unittest.mock import Mock, patch, MagicMock, PropertyMock
88
from dataclasses import dataclass
99
import tempfile
1010

@@ -333,6 +333,85 @@ def test_list_deployment_configs_non_string_model(self):
333333
self.assertIn("only supported for JumpStart", str(context.exception))
334334

335335

336+
class TestPreDeployBenchmarkData(unittest.TestCase):
337+
"""Pre-deploy JumpStart benchmark data: list_deployment_configs() and the
338+
benchmark_metrics property must work before build()/deploy() is called.
339+
"""
340+
341+
def _jumpstart_mb(self):
342+
"""A JumpStart-config ModelBuilder, constructed the same way as
343+
TestFromJumpStartConfig (explicit role_arn, no live role/instance
344+
resolution)."""
345+
js_config = JumpStartConfig(model_id="test-model", model_version="1.0.0")
346+
return ModelBuilder.from_jumpstart_config(
347+
jumpstart_config=js_config,
348+
role_arn="arn:aws:iam::123456789012:role/SageMakerRole",
349+
)
350+
351+
def test_get_deployment_configs_ensures_metadata(self):
352+
"""_get_deployment_configs lazily loads metadata configs itself, so every
353+
caller benefits. Pre-fix it read _metadata_configs (None pre-deploy) and
354+
returned [] without ever loading them."""
355+
mb = self._jumpstart_mb()
356+
mb._metadata_configs = None
357+
358+
with patch.object(mb, "_ensure_metadata_configs") as ensure:
359+
result = mb._get_deployment_configs(None, None)
360+
361+
ensure.assert_called_once()
362+
self.assertEqual(result, [])
363+
364+
def test_list_deployment_configs_loads_metadata_when_pre_deploy(self):
365+
"""list_deployment_configs() with no instance_type returns configs for a
366+
pre-deploy JumpStart model instead of []."""
367+
mb = self._jumpstart_mb()
368+
mb.config_name = None
369+
mb.instance_type = None
370+
371+
with patch.object(mb, "_is_jumpstart_model_id", return_value=True), patch.object(
372+
mb, "_is_model_customization", return_value=False
373+
), patch.object(mb, "_use_jumpstart_equivalent", return_value=False), patch.object(
374+
mb, "_get_deployment_configs", return_value=[Mock()]
375+
), patch.object(
376+
mb, "deployment_config_response_data", return_value=[{"DeploymentConfigName": "c1"}]
377+
):
378+
result = mb.list_deployment_configs()
379+
380+
self.assertEqual(result, [{"DeploymentConfigName": "c1"}])
381+
382+
def test_benchmark_metrics_property_returns_dataframe(self):
383+
"""The benchmark_metrics property builds a DataFrame from the config
384+
benchmark data (it did not exist before, causing AttributeError)."""
385+
mb = self._jumpstart_mb()
386+
sample = {
387+
"Instance Type": ["ml.g5.2xlarge", "ml.g5.12xlarge"],
388+
"Latency (ms)": [100.0, 80.0],
389+
}
390+
391+
with patch.object(mb, "_get_deployment_configs_benchmarks_data", return_value=sample):
392+
df = mb.benchmark_metrics
393+
394+
self.assertEqual(list(df["Instance Type"]), ["ml.g5.2xlarge", "ml.g5.12xlarge"])
395+
396+
def test_display_benchmark_metrics_no_attribute_error(self):
397+
"""display_benchmark_metrics() reads the benchmark_metrics property and
398+
no longer raises AttributeError for a JumpStart model. The property is
399+
patched to a stand-in frame so the assertion is on the wiring, not on
400+
pandas' optional markdown renderer."""
401+
mb = self._jumpstart_mb()
402+
df = MagicMock()
403+
df.to_markdown.return_value = "table"
404+
405+
with patch.object(mb, "_is_jumpstart_model_id", return_value=True), patch.object(
406+
mb, "_use_jumpstart_equivalent", return_value=False
407+
), patch.object(
408+
type(mb), "benchmark_metrics", new_callable=PropertyMock, return_value=df
409+
):
410+
mb.display_benchmark_metrics()
411+
412+
df.to_markdown.assert_called_once()
413+
414+
336415
class TestTransformer(unittest.TestCase):
337416
"""Test transformer method."""
338417

0 commit comments

Comments
 (0)