Optimum 文档
Ryzen 推理管线
加入 Hugging Face 社区
并获得增强的文档体验
开始使用
Ryzen 推理管线
Pipelines 是使用模型进行推理的一种出色且简便的方法。这些 pipelines 是从库中抽象出大多数复杂代码的对象,提供了一个专用于多项任务的简单 API。
目前支持的任务有
图像分类
目标检测
(支持的模型类型 - yolox, yolov3, yolov5, yolov8)图像分割
(支持的模型类型 - hrnet, semantic_fpn)
Pipeline 抽象
Pipeline 抽象是所有可用 pipelines 的包装器,用于特定任务。 pipeline()
函数自动加载默认模型和 tokenizer/特征提取器,能够为您的任务执行推理。
- 首先通过指定推理任务来创建 pipeline
>>> from optimum.amd.ryzenai import pipeline
>>> detector = pipeline("object-detection")
- 将您的输入文本/图像传递给
~pipelines.pipeline
函数
>>> import requests
>>> from PIL import Image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> detector(image)
[ { 'box': {'xmax': 325, 'xmin': 2, 'ymax': 465, 'ymin': 50},
'label': 15.0,
'score': 0.7081549763679504},
{ 'box': {'xmax': 630, 'xmin': 347, 'ymax': 381, 'ymin': 16},
'label': 15.0,
'score': 0.6494212746620178},
{ 'box': {'xmax': 369, 'xmin': 335, 'ymax': 187, 'ymin': 76},
'label': 65.0,
'score': 0.6064183115959167},
{ 'box': {'xmax': 645, 'xmin': 2, 'ymax': 475, 'ymin': 4},
'label': 57.0,
'score': 0.599224865436554},
{ 'box': {'xmax': 174, 'xmin': 40, 'ymax': 116, 'ymin': 73},
'label': 65.0,
'score': 0.408765971660614}]
使用来自 Hugging Face Hub 的 RyzenAI 模型进行推理
pipeline()
函数可以从 Hugging Face Hub 加载 Ryzen AI 支持的模型。一旦您选择了合适的模型,您可以通过指定模型仓库来创建 pipeline()
>>> import requests
>>> from PIL import Image
>>> from optimum.amd.ryzenai import pipeline
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # Hugging Face hub model-id with the quantized ONNX model
>>> model_id = "mohitsha/timm-resnet18-onnx-quantized-ryzen"
>>> pipe = pipeline("image-classification", model=model_id)
>>> print(pipe(image))
使用 RyzenModelForXXX 类
也可以使用 RyzenModelForXXX
类加载模型。例如,以下是如何为图像分类加载 ~ryzenai.RyzenModelForImageClassification
类
>>> import requests
>>> from PIL import Image
>>> from optimum.amd.ryzenai import RyzenAIModelForImageClassification
>>> from optimum.amd.ryzenai import pipeline
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # Hugging Face hub model-id with the quantized ONNX model
>>> model_id = "mohitsha/timm-resnet18-onnx-quantized-ryzen"
>>> model = RyzenAIModelForImageClassification.from_pretrained(model_id)
>>> pipe = pipeline("image-classification", model=model)
>>> print(pipe(image))
使用 model_type 参数
对于某些模型,除了 model_id 之外,还必须提供 model_type
和/或 image_preprocessor
才能进行推理。例如,以下是如何使用 yolox
运行推理
>>> import requests
>>> from PIL import Image
>>> from optimum.amd.ryzenai import pipeline
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> model_id = "amd/yolox-s"
>>> pipe = pipeline("object-detection", model=model_id, model_type="yolox")
>>> print(pipe(image))