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