|
from functools import partial |
|
|
|
from optimum.amd.ryzenai import ( |
|
AutoQuantizationConfig, |
|
RyzenAIOnnxQuantizer, |
|
) |
|
from optimum.exporters.onnx import main_export |
|
from transformers import AutoFeatureExtractor |
|
|
|
|
|
|
|
export_dir = "resnet_onnx" |
|
quantization_dir = "resnet_onnx_quantized" |
|
|
|
|
|
model_id = "microsoft/resnet-18" |
|
|
|
|
|
main_export( |
|
model_name_or_path=model_id, |
|
output=export_dir, |
|
task="image-classification", |
|
opset=13, |
|
batch_size=1, |
|
height=224, |
|
width=224, |
|
no_dynamic_axes=True, |
|
) |
|
|
|
|
|
feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) |
|
|
|
|
|
def preprocess_fn(ex, feature_extractor): |
|
image = ex["image"] |
|
if image.mode == "L": |
|
image = image.convert("RGB") |
|
pixel_values = feature_extractor(image).pixel_values[0] |
|
return {"pixel_values": pixel_values} |
|
|
|
|
|
|
|
quantizer = RyzenAIOnnxQuantizer.from_pretrained(export_dir) |
|
|
|
|
|
quantization_config = AutoQuantizationConfig.ipu_cnn_config() |
|
|
|
|
|
train_calibration_dataset = quantizer.get_calibration_dataset( |
|
"imagenet-1k", |
|
preprocess_function=partial(preprocess_fn, feature_extractor=feature_extractor), |
|
num_samples=100, |
|
dataset_split="train", |
|
preprocess_batch=False, |
|
streaming=True, |
|
) |
|
|
|
|
|
quantizer.quantize( |
|
quantization_config=quantization_config, dataset=train_calibration_dataset, save_dir=quantization_dir |
|
) |
|
|