Optimum 文档
Ryzen 推理管道
加入 Hugging Face 社区
并获得增强的文档体验
开始使用
Ryzen 推理管道
管道是使用模型进行推理的绝佳且简便的方法。这些管道是抽象库中大部分复杂代码的对象,为多项任务提供简单的 API。
目前支持的任务有
图像分类
目标检测
(支持的模型类型 - yolox, yolov3, yolov5, yolov8)图像分割
(支持的模型类型 - hrnet, semantic_fpn)
管道抽象
管道抽象是围绕所有可用于特定任务的管道的包装器。`pipeline()` 函数会自动加载一个默认模型和 tokenizer/feature-extractor,能够为你的任务执行推理。
- 首先通过指定推理任务来创建管道
>>> 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))