对于许多数据科学家和机器学习工程师来说,大规模部署模型可能是一项繁琐的任务。 但是,Amazon SageMaker 终端节点为部署和扩展机器学习 (ML) 模型推理提供了一个简单的解决方案。 我们的最后 博客文章 和 GitHub回购 主持一个 YOLOv5 TensorFlowModel
on 亚马逊SageMaker 端点 引起了我们读者的极大兴趣。 许多读者也有兴趣学习如何使用托管 YOLOv5 模型 PyTorch
. 为了解决这个问题,最近发布了 YOLOv8 来自的模型 超力,我们介绍了这篇关于如何托管 YOLOv8 的文章 PyTorchModel
在 SageMaker 端点上。 YOLOv8 模型在 GNU GPL3 许可下分发,是一种流行的对象检测模型,以其运行时效率和检测准确性而闻名。 Amazon SageMaker 终端节点为模型部署提供了一个易于扩展且成本优化的解决方案。
解决方案概述
下图概述了用于使用 SageMaker 终端节点托管 YOLOv8 模型并以用户身份调用终端节点的 AWS 服务。 该解决方案使用 AWS CloudFormation 自动创建 SageMaker 实例并克隆我们的 GitHub上 存储库到实例。 SageMaker notebook 访问并下载 YOLOv8 PyTorch 模型并将自定义推理代码与模型一起存储在 亚马逊简单存储服务 (亚马逊 S3)桶。 笔记本中的步骤突出显示了托管 YOLOv8 PyTorch 模型和自定义推理代码的 SageMaker 端点的创建。 该笔记本还演示了如何测试端点并绘制结果。 该解决方案包括以下步骤:
- 我们已经用两个笔记本创建了一个 GitHub 存储库
1_DeployEndpoint.ipynb
和2_TestEndpoint.ipynb
,在sm-notebook/
目录。 - AWS CloudFormation 模板运行,创建 SageMaker Notebook 实例,然后克隆 GitHub 存储库。
- 笔记本
1_DeployEndpoint.ipynb
用于下载YOLOv8模型。 - YOLOv8 模型和推理代码存储为
model.tar.gz
在亚马逊 S3 中。 - SageMaker 端点是通过托管
model.tar.gz
. - 笔记本
2_TestEndpoint.ipynb
用于测试端点并收集结果。
先决条件
AWS 账户 AWS Identity and Access Management (IAM) 角色 提供对以下内容的访问:
- AWS CloudFormation
- 亚马逊SageMaker
- Amazon S3
1. 在 SageMaker 端点上托管 YOLOv8
Ultralytics 有多个具有不同功能的 YOLOv8 模型。 它们分为以下几类:
- 物体检测 (
yolov8l.pt, yolov8m.pt, yolov8n.pt, yolov8s.pt, yolov8x.pt, yolov8x6.pt
) - 用户分类 (
yolov8l-seg.pt, yolov8m-seg.pt, yolov8n-seg.pt, yolov8s-seg.pt, yolov8x-seg.pt
) - 分类 (
yolov8l-cls.pt, yolov8m-cls.pt, yolov8n-cls.pt, yolov8s-cls.pt, yolov8x-cls.pt
)
在这篇博客中,我们专注于使用对象检测 yolov8l.pt
PyTorch 模型。 为了在 SageMaker 端点上托管 YOLOv8 模型和自定义推理代码,需要将它们压缩到一个单一的 model.tar.gz
具有以下结构:
model.tar.gz ├─ code/ │ ├── inference.py │ └── requirements.txt └── yolov8l.pt
模型权重 yolov8l.pt
文件必须在 code/
目录和主要推理python脚本 inference.py
,其中包含加载模型、解析输入、运行推理和后处理输出所需的函数,应该位于 code/
目录。 更多详细信息 inference.py
在下一节中介绍。
1.1. 自定义推理代码
根据您的管道和代码工作流程,SageMaker 端点的输入和输出可能会有所不同。 在这篇文章中,我们展示了一个用于传递 numpy
数组到端点和处理。 但是,端点的输入可以是 json
或文本也是如此。 根据您的工作流程,您必须修改中的功能 inference.py
以适应不同的输入和输出。 此外,随着最近发布的 YOLOv8,Ultralytics 团队发布了他们的 Python API,这使我们可以直接通过以下方式安装 YOLO 库 requirements.txt
并将模型导入 inference.py
.
1.1.1. 的内容 code/inference.py
:
import numpy as np
import torch, os, json, io, cv2, time
from ultralytics import YOLO def model_fn(model_dir): print("Executing model_fn from inference.py ...") env = os.environ model = YOLO("/opt/ml/model/code/" + env['YOLOV8_MODEL']) return model def input_fn(request_body, request_content_type): print("Executing input_fn from inference.py ...") if request_content_type: jpg_original = np.load(io.BytesIO(request_body), allow_pickle=True) jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8) img = cv2.imdecode(jpg_as_np, flags=-1) else: raise Exception("Unsupported content type: " + request_content_type) return img def predict_fn(input_data, model): print("Executing predict_fn from inference.py ...") device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) with torch.no_grad(): result = model(input_data) return result def output_fn(prediction_output, content_type): print("Executing output_fn from inference.py ...") infer = {} for result in prediction_output: if result.boxes: infer['boxes'] = result.boxes.numpy().data.tolist() if result.masks: infer['masks'] = result.masks.numpy().data.tolist() if result.probs: infer['probs'] = result.probs.numpy().data.tolist() return json.dumps(infer)
1.1.2. 的内容 code/requirements.txt
:
一旦所有文件内容为 model.tar.gz
完成后,运行以下命令创建一个 tar 包:
$ tar -czvf model.tar.gz code/ yolov8l.pt
1.2.主持人 model.tar.gz
到 SageMaker 端点:
这涉及几个步骤,其中 model.tar.gz
首先上传到 S3 存储桶。 上传的工件用于创建 SageMaker PyTorchModel。 最后,此 PyTorchModel 用于将模型部署到 SageMaker 端点。
1.2.1. 将模型和推理代码上传到 S3:
from sagemaker import s3 bucket = "s3://NAME_OF_BUCKET"
prefix = "yolov8/demo-custom-endpoint"
model_data = s3.S3Uploader.upload("model.tar.gz", bucket + "/" + prefix)
1.2.2. 创建 SageMaker PyTorchModel:
from sagemaker.pytorch import PyTorchModel model_name = 'yolov8l.pt' model = PyTorchModel(entry_point='inference.py', model_data=model_data, framework_version='1.12', py_version='py38', role=role, env={'TS_MAX_RESPONSE_SIZE':'20000000', 'YOLOV8_MODEL': model_name}, sagemaker_session=sess)
1.2.3. 编译模型并将其托管到端点:
from sagemaker.deserializers import JSONDeserializer INSTANCE_TYPE = 'ml.m5.4xlarge'
ENDPOINT_NAME = 'yolov8-pytorch-' + str(datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S-%f')) predictor = model.deploy(initial_instance_count=1, instance_type=INSTANCE_TYPE, deserializer=JSONDeserializer(), endpoint_name=ENDPOINT_NAME)
2. 测试 SageMaker 端点
端点成功托管后,即可用于运行推理。 在此步骤中,我们将首先读取图像,将其转换为字节并通过将字节作为输入传递给端点来运行推理。 根据用于托管的 YOLOv8 模型的类型,生成的结果将具有边界框或掩码或置信度分数。 可以相应地绘制输出。
2.1.1. 生成推理结果和绘图输出:
import cv2, random
import numpy as np
import matplotlib.pyplot as plt orig_image = cv2.imread('bus.jpg') image_height, image_width, _ = orig_image.shape
model_height, model_width = 300, 300
x_ratio = image_width/model_width
y_ratio = image_height/model_height resized_image = cv2.resize(orig_image, (model_height, model_width))
payload = cv2.imencode('.jpg', resized_image)[1].tobytes()
result = predictor.predict(payload) if 'boxes' in result: for idx,(x1,y1,x2,y2,conf,lbl) in enumerate(result['boxes']): # Draw Bounding Boxes x1, x2 = int(x_ratio*x1), int(x_ratio*x2) y1, y2 = int(y_ratio*y1), int(y_ratio*y2) color = (random.randint(10,255), random.randint(10,255), random.randint(10,255)) cv2.rectangle(orig_image, (x1,y1), (x2,y2), color, 4) cv2.putText(orig_image, f"Class: {int(lbl)}", (x1,y1-40), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2, cv2.LINE_AA) cv2.putText(orig_image, f"Conf: {int(conf*100)}", (x1,y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2, cv2.LINE_AA) if 'masks' in result: # Draw Masks mask = cv2.resize(np.asarray(result['masks'][idx]), dsize=(image_width, image_height), interpolation=cv2.INTER_CUBIC) for c in range(3): orig_image[:,:,c] = np.where(mask>0.5, orig_image[:,:,c]*(0.5)+0.5*color[c], orig_image[:,:,c]) if 'probs' in result: # Find Class lbl = result['probs'].index(max(result['probs'])) color = (random.randint(10,255), random.randint(10,255), random.randint(10,255)) cv2.putText(orig_image, f"Class: {int(lbl)}", (20,20), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2, cv2.LINE_AA) plt.imshow(cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB))
plt.show()
2.1.2。 结果:
目标检测和分割 YOLOv8 模型的输出如下图所示:
3。 清理
删除 CloudFormation 堆栈 将删除最初创建的所有资源。 但是,CloudFormation 当前未配置为自动删除端点、端点配置和模型。 如果未使用托管端点,最好将其删除以节省成本。 可以按如下方式完成:
import boto3 sm_client = boto3.client(service_name="sagemaker") response = sm_client.describe_endpoint_config(EndpointConfigName=endpoint_name)
print(response)
endpoint_config_name = response['EndpointConfigName'] # Delete Endpoint
sm_client.delete_endpoint(EndpointName=endpoint_name) # Delete Endpoint Configuration
sm_client.delete_endpoint_config(EndpointConfigName=endpoint_config_name) # Delete Model
for prod_var in response['ProductionVariants']: model_name = prod_var['ModelName'] sm_client.delete_model(ModelName=model_name)
结论
在这篇文章中,我们演示了如何托管预训练的 YOLOv8 PyTorchModel
在 SageMaker 端点上,并通过调用端点来测试推理结果。 详细代码可在 GitHub上,模板 CloudFormation 堆栈也可在 GitHub 上获得。
要了解有关 SageMaker 端点的更多信息,请查看 创建您的端点并部署您的模型 和 将 PyTorch 与 Amazon SageMaker 结合使用,突出显示使用 PyTorchModel
在 SageMaker 上。 该过程可以使用自动化 CloudFormation 对 SageMaker 的支持.
关于作者
凯文·宋 是 AWS 专业服务的数据科学家。 他拥有生物物理学博士学位,在构建计算机视觉和机器学习解决方案方面拥有超过五年的行业经验。
罗米尔沙阿 是 AWS Professional Services 的 IoT Edge 数据科学家。 Romil 在计算机视觉、机器学习和物联网边缘设备方面拥有超过六年的行业经验。 他参与帮助客户为工业设置中的边缘设备优化和部署机器学习模型。
- SEO 支持的内容和 PR 分发。 今天得到放大。
- 柏拉图区块链。 Web3 元宇宙智能。 知识放大。 访问这里。
- Sumber: https://aws.amazon.com/blogs/machine-learning/hosting-yolov8-pytorch-model-on-amazon-sagemaker-endpoints/
- :是
- 1
- 10
- 100
- 7
- a
- 关于
- ACCESS
- 容纳
- 因此
- 账号管理
- 增加
- 地址
- 所有类型
- 允许
- Amazon
- 亚马逊SageMaker
- 和
- API
- 保健
- 排列
- AS
- At
- 自动化
- 自动化
- 自动
- 可使用
- AWS
- AWS专业服务
- 球
- 基于
- BE
- 作为
- 生物物理学
- 博客
- 箱
- 建筑物
- 总线
- by
- CAN
- 能力
- 查
- 程
- 码
- 颜色
- COM的
- 一台
- 计算机视觉
- 信心
- 配置
- 包含
- 内容
- Contents
- 兑换
- 成本
- 创建信息图
- 创建
- 创建
- 创建
- 目前
- 习俗
- 合作伙伴
- data
- 数据科学家
- 日期时间
- 证明
- 演示
- 根据
- 部署
- 部署
- 部署
- 详细
- 详情
- 检测
- 设备
- 设备
- 不同
- 直接
- 分布
- 下载
- 下载
- 画
- 容易
- 边缘
- 效率
- 或
- 端点
- 工程师
- 执行
- 体验
- 少数
- 文件
- 敲定
- 终于
- 找到最适合您的地方
- (名字)
- 专注焦点
- 以下
- 如下
- 针对
- 止
- 功能
- 进一步
- 生成
- 产生
- GitHub上
- 非常好
- 有
- 帮助
- 近期亮点
- 亮点
- 持有
- 主持人
- 托管
- 托管
- 为了
- 创新中心
- How To
- 但是
- HTML
- HTTPS
- 身分
- IDX
- 图片
- 图片
- 进口
- in
- 产业
- 行业中的应用:
- 输入
- 安装
- 例
- 兴趣
- 有兴趣
- 参与
- 物联网
- 问题
- IT
- 它的
- JPG
- JSON
- 已知
- (姓氏)
- 学习用品
- 学习
- 自学资料库
- 执照
- 装载
- 占地
- 机
- 机器学习
- 主要
- 颠覆性技术
- 许多
- 面膜
- 面膜
- matplotlib
- ML
- 模型
- 模型
- 修改
- 更多
- 多
- 需求
- 笔记本
- 麻木
- 对象
- 物体检测
- of
- on
- 优化
- 秩序
- 本来
- OS
- 大纲
- 产量
- 学校以外
- 通过
- 管道
- 柏拉图
- 柏拉图数据智能
- 柏拉图数据
- 请
- 热门
- 帖子
- 在练习上
- 预报器
- 当下
- 呈现
- 过程
- 处理
- 所以专业
- 提供
- 提供
- 蟒蛇
- pytorch
- 提高
- 随机
- 阅读
- 读者
- 最近
- 释放
- 发布
- 去掉
- 知识库
- 岗位要求
- 资源
- 响应
- 导致
- 成果
- 回报
- 运行
- 运行
- sagemaker
- 保存
- 可扩展性
- 鳞片
- 缩放
- 科学家
- 科学家
- 海生的
- 部分
- 分割
- 特色服务
- 格局
- 形状
- 应该
- 如图
- 简易
- 单
- SIX
- 方案,
- 解决方案
- 堆
- 步
- 步骤
- 存储
- 存储
- 商店
- 结构体
- 顺利
- SUPPORT
- 任务
- 团队
- 模板
- test
- 这
- 其
- 次
- 至
- 一起
- 火炬
- 火炬视
- 下
- 上传
- us
- 用户
- 愿景
- 井
- 这
- 将
- 中
- 将
- 年
- YOLO
- 完全
- 您一站式解决方案
- 和风网