AWS AI Blog短讯
使用 Amazon SageMaker JumpStart 部署和评估模型
本文介绍如何利用 Amazon SageMaker JumpStart 部署预置模型,通过 SageMaker Python SDK 运行轻量级且可重复的性能测试,并在测试结束后删除端点。
为特定应用选择合适的模型,需要一种使用代表性输入进行测试的实用方法。Amazon SageMaker JumpStart 提供了对广泛预训练模型目录的访问权限。在本文中,我们将展示如何从 SageMaker JumpStart 部署可用模型,使用 SageMaker Python SDK 运行轻量级且可重复的性能测试,并在测试完成后删除终端节点。对于支持的模型和可用容量,此工作流提供了一种可重复的评估路径,尽管部署时间因模型、实例类型、配额和 AWS 区域而异。
2026 年,SageMaker JumpStart 引入了两项改进,简化了模型的发现和部署。在 Amazon SageMaker AI 控制台的“模型中心”部分,您可以浏览 SageMaker JumpStart 目录,查看示例笔记本,并直接在 SageMaker Studio 中打开它们。预配置的终端节点部署选项提供了针对优先级优化的命名配置,例如低成本、低延迟或通用工作负载,适用于一系列生成式 AI 模型,包括经过 Neuron 优化的配置。此外,借助新的深度链接集成,您现在可以通过单击一次操作,从 Hugging Face 模型发现直接过渡到 SageMaker AI 部署。
解决方案概述
- 从 SageMaker JumpStart 发现和部署模型。
- 运行特定于模型的示例提示,并测量延迟、近似输出长度和单请求生成速率。
- 清理终端节点。
此模式适用于许多兼容的 SageMaker JumpStart 模型,尽管有效载荷格式、所需的实例类型、最终用户许可协议 (EULA) 要求以及响应模式可能需要针对特定模型进行调整。
先决条件
- 具有 SageMaker AI 权限的 AWS 账户。
- 安装了 SageMaker Python SDK v3 的 Python 3+(pip install "sagemaker>=3,<4")。
- 用于测试模型的足够 GPU 实例配额,或者请求增加配额。
步骤 1.a:发现可用模型

from sagemaker.core.jumpstart.notebook_utils import (
list_jumpstart_models,
)
REGION = "us-east-1"
models = list_jumpstart_models(
filter="task == textgeneration",
region=REGION,
list_versions=True,
)
print(f"Found {len(models)} text generation models")
for model_id, model_version in models[:10]:
print(
f" - {model_id} "
f"(version {model_version})"
)或按模型名称搜索:
from sagemaker.core.jumpstart.notebook_utils import list_jumpstart_models
ids = list_jumpstart_models(
filter="model_id contains qwen",
region=REGION,
list_versions=True,
)
print(f"{len(ids)} models matched in {REGION}\n")
for model_id, version in ids:
print(f"{model_id:<55} v{version}")步骤 1.b:部署模型

import time
from sagemaker.core.jumpstart.accessors import JumpStartModelsAccessor
from sagemaker.core.jumpstart.configs import JumpStartConfig
from sagemaker.core.training.configs import Compute
from sagemaker.serve import ModelBuilder
MODEL_ID = "huggingface-vlm-qwen3-5-27b"
MODEL_VERSION = "1.13.0"
REGION = "us-east-1"
ACCEPT_EULA = False # Set True only after reviewing the model terms
def get_field(value, name, default=None):
if isinstance(value, dict):
return value.get(name, default)
return getattr(value, name, default)
# Resolve the JumpStart-recommended deployment configuration.
specs = JumpStartModelsAccessor().get_model_specs(
region=REGION,
model_id=MODEL_ID,
version=MODEL_VERSION,
)
if isinstance(specs, list):
if not specs:
raise ValueError(
f"No JumpStart specification found for {MODEL_ID}"
)
specs = specs[0]
recommended_instance_type = get_field(
specs,
"default_inference_instance_type",
)
if not recommended_instance_type:
raise ValueError(
f"No recommended instance type found for {MODEL_ID}"
)
print(f"Model: {MODEL_ID}")
print(f"Region: {REGION}")
print(f"Recommended instance: {recommended_instance_type}")
start = time.time()
jumpstart_config = JumpStartConfig(
model_id=MODEL_ID,
model_version=MODEL_VERSION,
accept_eula=ACCEPT_EULA,
)
model_builder = ModelBuilder.from_jumpstart_config(
jumpstart_config=jumpstart_config,
compute=Compute(
instance_type=recommended_instance_type,
instance_count=1,
),
)
model = model_builder.build()
endpoint = model_builder.deploy()
deploy_time = time.time() - start
print(f"Deployed in {deploy_time:.1f} seconds")
print(f"Endpoint: {endpoint.endpoint_name}")步骤 2:运行示例提示并衡量性能
from sagemaker.core.payloads import retrieve_all_examples
import json
import time
MODEL_ID = "huggingface-vlm-qwen3-5-27b"
MODEL_VERSION = "1.13.0"
REGION = "us-east-1"
example_payloads = retrieve_all_examples(
region=REGION,
model_id=MODEL_ID,
model_version=MODEL_VERSION,
serialize=True,
)
#you can re-create the endpoint pointer using the endpoint name:
#from sagemaker.core.resources import Endpoint
#endpoint = Endpoint.get(endpoint_name="<your_endpoint_name>",region=REGION)
def read_response_body(result):
body = result.body
if hasattr(body, "read"):
body = body.read()
if isinstance(body, bytes):
body = body.decode("utf-8")
if isinstance(body, str):
try:
return json.loads(body)
except json.JSONDecodeError:
return body
return body
def extract_output(response):
"""Handle common JumpStart text-generation response formats."""
if isinstance(response, list):
response = response[0] if response else ""
if isinstance(response, dict):
choices = response.get("choices")
if choices:
choice = choices[0]
message = choice.get("message")
if isinstance(message, dict):
return message.get("content", "")
return choice.get("text", "")
for field in (
"generated_text",
"output_text",
"text",
):
if field in response:
return response[field]
return response
results = []
for payload in example_payloads or []:
start = time.perf_counter()
result = endpoint.invoke(
body=payload.body,
content_type=payload.content_type,
accept=payload.accept,
)
latency = time.perf_counter() - start
response = read_response_body(result)
output = extract_output(response)
if not isinstance(output, str):
output = json.dumps(output, indent=2)
# This is an estimate based on whitespace-separated words.
output_words = len(output.split())
results.append(
{
"request_preview": payload.body[:50],
"latency_s": round(latency, 2),
"estimated_output_words": output_words,
"words_per_second": round(
output_words / latency,
1,
) if latency > 0 else 0,
}
)
print("Input:\n", payload.body, end="\n\n")
print("Output:\n", output, end="\n\n")
print(
f"Latency: {latency:.2f} seconds\n"
f"Estimated output words: {output_words}\n"
f"Estimated single-request output generation rate: "
f"{output_words / latency:.1f} words/second\n"
)
print("-" * 80)
print("\nSummary:")
for result in results:
print(result)输入: {"max_tokens": 256, "messages": [{"content": "什么是深度学习?", "role": "user"}], "model": "/opt/ml/model"} 输出: 以下是推导对深度学习解释的思维过程: 1. 拆解请求: * 问题: “什么是深度学习?” * 意图: 用户希望获得一个清晰、全面且通俗易懂的定义和概述。 * 目标受众: 可能是寻求一般性理解的人,例如学生、科技爱好者或正在探索该领域的专业人士。语气应具信息量、结构清晰,且不过度使用行话(尽管需要对关键术语进行解释)。 2. 初步头脑风暴与核心概念: * 它是什么?机器学习的一个子集,而机器学习又是人工智能的一个子集。 * 核心机制:人工神经网络(ANNs)。 * “深度”意味着许多层(隐藏层)。 * 它是如何工作的?从数据中学习表示(特征学习)。 * 关键应用:图像识别、自然语言处理、语音、自动驾驶汽车。 * 为什么现在如此流行?大数据、GPU算力、更好的算法。 * 优缺点:高准确率 vs. 黑盒模型、对数据的渴求。 3. 构建答案结构: 延迟:9.07 秒 预估输出字数:153 预估单次请求输出生成速率:16.9 字/秒 -------------------------------------------------------------------------------- 摘要: {'request_preview': '{"max_tokens": 256, "messages": {"content": "What', 'latency_s': 9.07, 'estimated_output_words': 153, 'words_per_second': 16.9}
步骤 3:清理
print(f"Deleting endpoint: {endpoint.endpoint_name}")
endpoint.delete()
endpoint.wait_for_delete()
print("Endpoint deleted")结论
此模式适用于许多可用的 SageMaker JumpStart 模型,但有效载荷格式、所需的实例类型、最终用户许可协议 (EULA) 以及响应解析可能需要针对特定模型进行调整。通过使用一致的测试提示并衡量不同模型的延迟、吞吐量和输出质量,您可以比较选项并选择最适合您工作负载的方案。
尝试使用 Amazon SageMaker JumpStart 中的不同模型来找到适合您应用在质量、速度和成本之间的最佳平衡点。
参考文献
- SageMaker Python SDK 文档
- 基准测试和优化 SageMaker JumpStart 部署(博客文章)
- 一键式从 Hugging Face 到 SageMaker Studio(博客文章)
- Amazon SageMaker JumpStart
关于作者
译文已达到本站中文翻译的字数上限,剩余内容请查看原文。