-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7d5b7cf
commit 6eee583
Showing
2 changed files
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
# Copyright (C) 2018-2024 Intel Corporation | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
#! [dataset] | ||
import nncf | ||
import torch | ||
|
||
calibration_loader = torch.utils.data.DataLoader(...) | ||
|
||
def transform_fn(data_item): | ||
images, _ = data_item | ||
return images | ||
|
||
calibration_dataset = nncf.Dataset(calibration_loader, transform_fn) | ||
#! [dataset] | ||
|
||
#! [quantization] | ||
import torchvision | ||
import openvino.torch | ||
model = torchvision.models.resnet50(pretrained=True) | ||
|
||
input_fp32 = ... # FP32 model input | ||
|
||
with nncf.torch.disable_patching(): | ||
exported_model = torch.export.export(model, args=(input_fp32,)) | ||
quantized_model = nncf.quantize(model, calibration_dataset) | ||
#! [quantization] | ||
|
||
#! [inference] | ||
import openvino as ov | ||
|
||
input_fp32 = ... # FP32 model input | ||
|
||
# compile quantized model using torch.compile API | ||
with nncf.torch.disable_patching(): | ||
compiled_model_int8 = torch.compile(quantized_model, backend="openvino") | ||
# First call compiles an OpenVino model underneath, so it could take longer | ||
# than original model call. | ||
res = compiled_model_int8(input_fp32) | ||
... | ||
|
||
|
||
# convert exported Torch model to OpenVINO model | ||
with nncf.torch.disable_patching(): | ||
exported_quantized_model = torch.export.export(quantized_model, args=(input_fp32,)) | ||
ov_quantized_model = ov.convert_model(quantized_model, example_input=input_fp32) | ||
|
||
# compile the model to transform quantized operations to int8 | ||
model_int8 = ov.compile_model(ov_quantized_model) | ||
|
||
res = model_int8(input_fp32) | ||
|
||
# save the model | ||
ov.save_model(ov_quantized_model, "quantized_model.xml") | ||
#! [inference] |