AWS Machine Learning Blog

Deploy and evaluate models with Amazon SageMaker JumpStart

8.5内容质量
Deploy and evaluate models with Amazon SageMaker JumpStart

TL;DR · AI 摘要

AWS SageMaker JumpStart 提供了简化模型部署和评估的工具,支持预配置选项和单击集成,适用于多种生成式AI模型。

核心要点

  • 2026年新增Model Hub界面支持直接浏览和打开Notebook
  • 预配置部署选项包含低延迟/低成本优化方案
  • Hugging Face模型可单击集成到SageMaker部署

结构提纲

按章节快速跳转。

  1. 介绍模型选择需要实践测试,SageMaker JumpStart提供预训练模型目录。

  2. 新增Model Hub界面和预配置部署选项优化模型发现流程。

  3. 通过三步Python脚本实现模型部署、性能测试和资源清理。

  4. 包含UI路径和Python SDK代码示例进行模型发现与部署。

  5. 需要AWS账户、Python 3+及SageMaker SDK v3环境。

  6. 测试完成后需删除端点以避免持续费用。

思维导图

用一张图看清主题之间的关系。

查看大纲文本(无障碍 / 无 JS 友好)
  • SageMaker JumpStart部署方案
    • 核心功能
      • Model Hub界面
      • 预配置部署选项
      • Hugging Face集成
    • 实施步骤
      • 模型发现
      • Python脚本部署
      • 性能测试
      • 资源清理

金句 / Highlights

值得收藏与分享的关键句。

#Amazon SageMaker#机器学习#AWS#模型部署
打开原文

使用Amazon SageMaker JumpStart部署和评估模型 | 人工智能

使用Amazon SageMaker JumpStart部署和评估模型

为特定应用选择合适的模型需要一种实用的方法,通过具有代表性的输入进行测试。Amazon SageMaker JumpStart 提供了访问大量已预训练模型的目录。在本文中,我们将展示如何从 SageMaker JumpStart 部署可用模型,使用 SageMaker Python SDK 运行轻量且可重复的性能测试,并在测试完成后删除端点。对于支持的模型和可用容量,此工作流程提供了可重复的评估路径,尽管部署时间因模型、实例类型、配额和 AWS 区域而异。

2026 年,SageMaker JumpStart 引入了两项改进,简化了模型发现和部署。在 Amazon SageMaker AI 控制台的 Model Hub 部分,您可以浏览 SageMaker JumpStart 目录、查看示例笔记本并直接在 SageMaker Studio 中打开它们。预配置的端点部署选项提供了针对不同优先级(如低成本、低延迟或通用工作负载)优化的命名配置,涵盖多种生成式 AI 模型,包括 Neuron 优化配置。此外,现在可以通过新深度链接集成,单击即可从 Hugging Face 模型发现直接跳转到 SageMaker AI 部署。

解决方案概述

我们的方法使用一个可重复使用的 Python 脚本,执行以下三个步骤:

  • 从 SageMaker JumpStart 发现并部署模型。
  • 运行特定于模型的示例提示,测量延迟、输出长度估算值和单次请求生成速率。
  • 清理端点。

此模式适用于许多兼容的 SageMaker JumpStart 模型,尽管有效负载格式、所需的实例类型、最终用户许可协议 (EULA) 要求和响应模式可能需要特定于模型的调整。

先决条件

  • 具有 SageMaker AI 权限的 AWS 账户。
  • 安装了 SageMaker Python SDK v3 的 Python 3+(pip install "sagemaker>=3,<4")。
  • 足够的 GPU 实例配额用于您要测试的模型,或请求配额增加。

第 1.a 步:发现可用模型

在 SageMaker JumpStart 中查找模型的 UI 路径:

图 1:在 SageMaker Studio 的 SageMaker JumpStart 模型页面上浏览模型目录

使用 SageMaker Python SDK 的代码路径:

code
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})"
    )

或通过模型名称搜索:

code
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 步:部署模型

从 SageMaker JumpStart 部署模型的 UI 路径:

图 2:在 SageMaker Studio 的 SageMaker JumpStart 详细页面上部署模型

code
import time
python
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  # 仅在查看模型条款后设置为True

def get_field(value, name, default=None):
    if isinstance(value, dict):
        return value.get(name, default)
    return getattr(value, name, default)

# 获取JumpStart推荐的部署配置
specs = JumpStartModelsAccessor().get_model_specs(
    region=REGION,
    model_id=MODEL_ID,
    version=MODEL_VERSION,
)

if isinstance(specs, list):
    if not specs:
        raise ValueError(
            f"未找到 {MODEL_ID} 的JumpStart配置"
        )
    specs = specs[0]

recommended_instance_type = get_field(
    specs,
    "default_inference_instance_type",
)

if not recommended_instance_type:
    raise ValueError(
        f"未找到 {MODEL_ID} 的推荐实例类型"
    )

print(f"模型: {MODEL_ID}")
print(f"区域: {REGION}")
print(f"推荐实例: {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"部署耗时 {deploy_time:.1f} 秒")
print(f"端点: {endpoint.endpoint_name}")

第2步:运行示例提示并测量性能

code
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,
)

# 可以使用端点名称重新创建端点指针:
#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):
    """处理常见的JumpStart文本生成响应格式"""
    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 = []
python
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)
    # 这是基于空格分隔单词的估算
    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("输入:\n", payload.body, end="\n\n")
    print("输出:\n", output, end="\n\n")
    print(
        f"延迟: {latency:.2f} 秒\n"
        f"预估输出单词数: {output_words}\n"
        f"单次请求输出生成速率: "
        f"{output_words / latency:.1f} 单词/秒\n"
    )
    print("-" * 80)
python
print("\n摘要:")
for result in results:
    print(result)
code
输出结果:

输入:
{"max_tokens": 256, "messages": [{"content": "What is deep learning?", "role": "user"}], "model": "/opt/ml/model"}
输出:
这是一个引导至深度学习解释的思考过程:
1. **拆解请求:**
* **问题:** "什么是深度学习?"
* **意图:** 用户希望获得清晰、全面且易懂的定义和概述。
* **目标受众:** 可能是寻求一般性理解的人,可能是学生、科技爱好者或正在探索该领域的人士。语气应为信息性、结构化且不过度使用术语(但关键术语需要解释)。
2. **初步头脑风暴与核心概念:**
* 什么是深度学习?机器学习的子集,而机器学习又是人工智能的子集。
* 核心机制:人工神经网络(ANN)。
* "深度"意味着许多层(隐藏层)。
* 它如何运作?从数据中学习表示(特征学习)。
* 关键应用:图像识别、自然语言处理、语音识别、自动驾驶汽车。
* 为什么现在流行?大数据、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}

第三步:清理

python
print(f"正在删除端点: {endpoint.endpoint_name}")
endpoint.delete()
endpoint.wait_for_delete()
print("端点已删除")

结论

此模式适用于许多可用的SageMaker JumpStart模型,但有效载荷格式、所需实例类型、EULA和响应解析可能需要针对特定模型进行调整。通过使用一致的测试提示并在模型间测量延迟、吞吐量和输出质量,您可以比较选项并选择最适合您工作负载的方案。

尝试使用Amazon SageMaker JumpStart的不同模型,找到适合您应用的质量、速度和成本的最佳平衡。

参考文献

  • SageMaker Python SDK 文档
  • 对 SageMaker JumpStart 部署进行基准测试和优化 (博客文章)
  • 从 Hugging Face 一键部署到 SageMaker Studio (博客文章)
  • Amazon SageMaker JumpStart

关于作者

'"`