开始使用

在 Amazon SageMaker 端点上部署 YOLO26 指南

Amazon SageMaker Endpoints 为生产环境中的计算机视觉模型(如 Ultralytics YOLO26)提供托管式、可扩展的服务,用于构建机器学习应用。要成功部署模型,需要了解模型端和 AWS 端的设置、配置与部署步骤。

本指南将逐步介绍如何在 Amazon SageMaker 端点上部署 YOLO26 PyTorch 模型。你将了解准备 AWS 环境、正确配置模型,以及使用 AWS CloudFormation 和 AWS 云开发工具包 (CDK) 等工具进行部署的基本方法。

Amazon SageMaker#

Amazon SageMaker ML platform architecture

Amazon SageMaker 是 Amazon Web Services (AWS) 提供的一项机器学习服务,可简化机器学习模型的构建、训练和部署流程。它提供了各种工具,帮助你处理机器学习工作流的多个环节,包括用于调整模型的自动化功能、用于大规模训练模型的选项,以及将模型部署到生产环境的简便方法。SageMaker 支持常用的机器学习框架,为各种项目提供所需的灵活性。它的功能还涵盖数据标注、工作流管理和性能分析。

在 Amazon SageMaker 端点上部署 YOLO26#

在 Amazon SageMaker 上部署 YOLO26,可利用其托管环境进行实时推理,并使用自动扩缩容等功能。请查看下方的 AWS 架构。

AWS architecture for hosting YOLO on an Amazon SageMaker endpoint

步骤 1:设置 AWS 环境#

首先,确保已满足以下先决条件:

  • AWS 账户:如果你还没有 AWS 账户,请注册一个。

  • 已配置的 IAM 角色:你需要一个具备 Amazon SageMaker、AWS CloudFormation 和 Amazon S3 所需权限的 IAM 角色。该角色应附加允许其访问这些服务的策略。

  • AWS CLI:如果尚未安装,请下载并安装 AWS 命令行界面 (CLI),并使用你的账户信息进行配置。请按照 AWS CLI 安装说明进行安装。

  • AWS CDK:如果尚未安装,请安装 AWS 云开发工具包 (CDK),以便编写部署脚本。请按照 AWS CDK 安装说明进行安装。

  • 充足的服务配额:确认你在 Amazon SageMaker 中为两种不同资源预留了足够的配额:一种用于端点,配额项为 ml.m5.4xlarge;另一种用于笔记本实例,配额项为 ml.m5.4xlarge。这两种资源的配额值都至少需要为 1。如果当前配额低于此要求,请务必分别申请增加。你可以按照 AWS 服务配额文档中的详细说明申请增加配额。

步骤 2:克隆 YOLO26 SageMaker 仓库#

下一步是克隆包含在 SageMaker 上部署 YOLO26 所需资源的 AWS 专用仓库。该仓库托管在 GitHub 上,包含必要的 CDK 脚本和配置文件。

  • 克隆 GitHub 仓库:在终端中执行以下命令,克隆 host-yolov8-on-sagemaker-endpoint 仓库:

    git clone https://github.com/aws-samples/host-yolov8-on-sagemaker-endpoint.git
  • 进入克隆后的目录:将当前目录切换到克隆的仓库:

    cd host-yolov8-on-sagemaker-endpoint/yolov8-pytorch-cdk

步骤 3:设置 CDK 环境#

现在你已获得所需代码,可以设置使用 AWS CDK 进行部署的环境。

  • 创建 Python 虚拟环境:这可以隔离你的 Python 环境和依赖项。运行:

    python3 -m venv .venv
  • 激活虚拟环境:

    source .venv/bin/activate
  • 安装依赖项:安装项目所需的 Python 依赖项:

    pip3 install -r requirements.txt
  • 升级 AWS CDK 库:确保使用最新版本的 AWS CDK 库:

    pip install --upgrade aws-cdk-lib

步骤 4:创建 AWS CloudFormation 堆栈#

  • 合成 CDK 应用:根据你的 CDK 代码生成 AWS CloudFormation 模板:

    cdk synth
  • 引导 CDK 应用:为 AWS 环境做好 CDK 部署准备:

    cdk bootstrap
  • 部署堆栈:这将创建所需的 AWS 资源并部署模型:

    cdk deploy

步骤 5:部署 YOLO 模型#

创建 AWS CloudFormation 堆栈后,下一步就是部署 YOLO26。

  • 打开笔记本实例:前往 AWS 控制台并导航到 Amazon SageMaker 服务。在控制面板中选择“笔记本实例”,然后找到 CDK 部署脚本创建的笔记本实例。打开该笔记本实例以访问 Jupyter 环境。

  • 访问并修改 inference.py:在 Jupyter 中打开 SageMaker 笔记本实例后,找到 inference.py 文件。按下方所示编辑 inference.py 中的 output_fn 函数,并保存脚本更改,确保没有语法错误。

    import json
    
    def output_fn(prediction_output, content_type):
        """Formats model outputs as JSON string, extracting attributes like boxes, masks, keypoints."""
        print("Executing output_fn from inference.py ...")
        infer = {}
        for result in prediction_output:
            if result.boxes is not None:
                infer["boxes"] = result.boxes.numpy().data.tolist()
            if result.masks is not None:
                infer["masks"] = result.masks.numpy().data.tolist()
            if result.keypoints is not None:
                infer["keypoints"] = result.keypoints.numpy().data.tolist()
            if result.obb is not None:
                infer["obb"] = result.obb.numpy().data.tolist()
            if result.probs is not None:
                infer["probs"] = result.probs.numpy().data.tolist()
        return json.dumps(infer)
  • 使用 1_DeployEndpoint.ipynb 部署端点:在 Jupyter 环境中,打开 sm-notebook 目录下的 1_DeployEndpoint.ipynb 笔记本。将笔记本中的 model_name 设置为 YOLO26 检查点,例如 yolo26n.pt(默认使用 YOLOv8 模型),然后运行各个单元格,下载模型、使用更新后的推理代码打包模型,并将其上传到 Amazon S3 存储桶。笔记本将引导你创建并部署 YOLO26 模型的 SageMaker 端点。

步骤 6:测试部署#

现在 YOLO26 模型已完成部署,接下来要测试其性能和功能。

  • 打开测试笔记本:在同一个 Jupyter 环境中,找到并打开同样位于 sm-notebook 目录中的 2_TestEndpoint.ipynb 笔记本。

  • 运行测试笔记本:按照笔记本中的说明测试已部署的 SageMaker 端点,包括向端点发送图像并运行推理。然后,按照下方所示绘制输出结果,以直观地查看模型的性能和准确率。

YOLO26 detection results returned by the SageMaker test endpoint

  • 清理资源:测试笔记本还会指导你清理端点和托管模型。有效管理成本和资源非常重要,尤其是在你暂时不打算使用已部署模型的情况下。

步骤 7:监控和管理#

测试完成后,持续监控和管理已部署的模型至关重要。

  • 使用 Amazon CloudWatch 进行监控:定期使用 Amazon CloudWatch 检查 SageMaker 端点的性能和运行状况。

  • 管理端点:使用 SageMaker 控制台持续管理端点,包括根据需要扩缩、更新或重新部署模型。

完成这些步骤后,你便已在 Amazon SageMaker Endpoints 上部署并测试 YOLO26 模型。同样的工作流也适用于在 AWS 上部署其他模型。

总结#

本指南逐步介绍了如何使用 AWS CloudFormation 和 AWS Cloud Development Kit (CDK) 在 Amazon SageMaker Endpoints 上部署 YOLO26。流程包括克隆 AWS 机器学习博客文章中关于在 Amazon SageMaker Endpoints 上托管 YOLOv8 PyTorch 模型的 AWS 示例仓库、设置 CDK 环境、使用 AWS 服务部署模型,以及在 SageMaker 上测试模型性能。

常见问题#

  • 要在 Amazon SageMaker Endpoints 上部署 Ultralytics YOLO26 模型,请按以下步骤操作:

    1. 设置 AWS 环境:确保你拥有 AWS 账户、具有必要权限的 IAM 角色,并已配置 AWS CLI。如果尚未安装 AWS CDK,请先安装(参阅 AWS CDK 说明)。
    2. 克隆 YOLO26 SageMaker 代码库:
      git clone https://github.com/aws-samples/host-yolov8-on-sagemaker-endpoint.git
      cd host-yolov8-on-sagemaker-endpoint/yolov8-pytorch-cdk
    3. 设置 CDK 环境:创建并激活 Python 虚拟环境、安装依赖项,并升级 AWS CDK 库。
      python3 -m venv .venv
      source .venv/bin/activate
      pip3 install -r requirements.txt
      pip install --upgrade aws-cdk-lib
    4. 使用 AWS CDK 部署:合成并部署 CloudFormation 堆栈,然后引导初始化环境。
      cdk synth
      cdk bootstrap
      cdk deploy
  • 如需在 Amazon SageMaker 上部署 YOLO26,请确保满足以下先决条件:

    1. AWS 账户:有效的 AWS 账户(注册 AWS)。
    2. IAM 角色:已配置具有 SageMaker、CloudFormation 和 Amazon S3 权限的 IAM 角色。
    3. AWS CLI:已安装并配置 AWS 命令行界面(AWS CLI 安装指南)。
    4. AWS CDK:已安装 AWS 云开发工具包(CDK 设置指南)。
    5. 服务配额:ml.m5.4xlarge 实例的配额充足,可用于端点和笔记本(申请提高配额)。
  • 在 Amazon SageMaker 上使用 Ultralytics YOLO26 有以下优势:

    1. 可扩展性和管理:SageMaker 提供托管环境和自动扩缩等功能,有助于满足实时推理需求。
    2. 与 AWS 服务集成:与其他 AWS 服务集成,例如用于数据存储的 S3、用于基础设施即代码的 CloudFormation,以及用于监控的 CloudWatch。
    3. 便于部署:借助 AWS CDK 脚本简化设置,并让部署流程更加顺畅。
    4. 性能:使用 Amazon SageMaker 的托管基础设施运行大规模推理工作负载。
  • 可以,你可以自定义 YOLO26 在 Amazon SageMaker 上的推理逻辑:

    1. 修改 inference.py:在 inference.py 文件中找到并自定义 output_fn 函数,以调整输出格式。

      import json
      
      def output_fn(prediction_output, content_type):
          """Formats model outputs as JSON string, extracting attributes like boxes, masks, keypoints."""
          infer = {}
          for result in prediction_output:
              if result.boxes is not None:
                  infer["boxes"] = result.boxes.numpy().data.tolist()
              # 如有必要,添加更多处理逻辑
          return json.dumps(infer)
    2. 部署更新后的模型:确保使用提供的 Jupyter 笔记本(1_DeployEndpoint.ipynb)重新部署模型,以纳入这些更改。

    参阅详细步骤,了解如何部署修改后的模型。

  • 要在 Amazon SageMaker 上测试已部署的 YOLO26 模型,请执行以下操作:

    1. 打开测试笔记本:在 SageMaker Jupyter 环境中找到 2_TestEndpoint.ipynb 笔记本。
    2. 运行笔记本:按照笔记本中的说明向端点发送图像、执行推理并显示结果。
    3. 可视化结果:使用笔记本中的绘图代码,在测试图像上绘制预测边界框。

    如需全面的测试说明,请访问测试部分。

评论10

提出问题、分享结果,或帮助其他人。

  1. User

    I want to upload the YOLOv8 model I trained on my own dataset to Jupyter, and then compress it into a model.tar.gz file following the official deployendpoint steps. However, when I use testendpoint, I encounter an error. If I rename my trained model to yolov8, the test succeeds, but it uses the original model from the official website instead of my custom one. How should I modify inference.py to ensure it loads my trained model?

    1
    1. User

      Thank you for your answer. I had followed the 1_DeployEndpoint.ipynb to delpoy my own model. In the 1.4 Create the SageMaker PyTorchModel, I had set the env={'TS_MAX_RESPONSE_SIZE':'20000000', 'MY_MODEL': 'my_own_model'}. And in the inference.py:

      def model_fn(model_dir):
          print("Executing model_fn from inference.py ...")
          env = os.environ
          model = YOLO(os.path.join(model_dir, env['MY_MODEL']))
          return model

      I think it will be use my own model directly. But it failed, and it occur this problem:

      ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (0)from primary with message "Your invocation timed out while waiting for a response from container primary. Reviewthe latency metrics for each container in Amazon Cloudatch, resolve the issue, and try again.". See https://useast-1. console. aws. aazon. com/cloudwatch/home?region=us-east-1#logEventViewer: group=/aws/sagemaker Endpoints/yolov8-pytorch-2024-09-06-11-33-49-418696 in account 211125332801 for more information.

      Could you tell me how to modify the inference.py to load my own model. Thank you so much.

    2. Glenn JocherUltralytics

      To ensure your custom YOLOv8 model is used, verify that the model_fn in inference.py correctly points to your model's path. Ensure the MY_MODEL environment variable matches your model's filename. If issues persist, check CloudWatch logs for detailed error messages. For further guidance, refer to the Ultralytics documentation on Amazon SageMaker.

  2. SJTUPandaGitHub

    Thanks for your sharing, it's very clear and useful. My own deployment workflow on AWS has already built but the test result is not so satisfying. The performance of detection result of yolo11-xl on AWS is worse than on my own laptop. I not sure if there is some default quantization when it's deployed to the AWS(I did not modified much to host-yolov8-on-sagemaker-endpoint), or do you have some other ideas about which would bring this significant performance differences?

    1. Glenn JocherUltralytics

      @SJTUPanda thank you for your feedback! The performance difference could stem from several factors like hardware disparities (AWS instance vs laptop GPU), inference settings, or environment configurations. First, verify that your SageMaker instance type matches your local hardware capabilities, and ensure identical inference parameters (e.g., imgsz, batch). Check our Amazon SageMaker deployment guide for optimization tips and consider profiling both environments with yolo val to isolate bottlenecks. Let us know if specific metrics differ! 🚀

    2. SJTUPandaGitHub

      Thanks for your quick reply. The issue is fixed after I comment out resize related code. Although the model is trained with (640,640) and the input image size is (720,440), using the raw images directly as input is better than resized it. I am curious the input images would be auto-resized by the model just as in the training/testing part? And why resized by myself has so much impact on the results? If these part code should be update because yolo version updating?

      image_height, image_width, _ = orig_image.shape
      model_height, model_width = 640, 640
      x_ratio = image_width/model_width
      y_ratio = image_height/model_height
      
      # Resize the image as numpy array
      resized_image = cv2.resize(orig_image, (model_height, model_width))
      # Conver the array into jpeg
      resized_jpeg = cv2.imencode('.jpg', resized_image)[1]
      # Serialize the jpg using base 64
      payload = base64.b64encode(resized_jpeg).decode('utf-8')
    3. Glenn JocherUltralytics

      Thank you for sharing your findings! YOLO models do automatically resize inputs to match their training dimensions while preserving aspect ratio with letterboxing. Manual resizing can distort aspect ratios or introduce artifacts, potentially degrading performance. We recommend using the model's native preprocessing by feeding full-size images directly, as this maintains proper scaling and aspect ratio handling. For implementation details, refer to our model deployment best practices regarding input consistency.

    1. Glenn JocherUltralytics

      Olá! 👋 Os recursos mencionados para implementar o YOLOv8 no Amazon SageMaker não são pagos por si só. No entanto, o uso do Amazon SageMaker e outros serviços da AWS associados à implementação e execução do modelo podem incorrer em custos conforme o uso. A AWS oferece uma camada gratuita que você pode aproveitar para experimentar alguns serviços sem custo, mas é sempre bom verificar a página de preços do SageMaker para detalhes específicos. Se precisar de ajuda para estimar os custos ou tiver outras dúvidas, estou aqui para ajudar! 🚀