|
| 1 | +# Copyright (C) 2024 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import time |
| 7 | +from pathlib import Path |
| 8 | +from zipfile import ZipFile |
| 9 | +from typing import Iterable |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +import datasets |
| 13 | +import numpy as np |
| 14 | +import nncf |
| 15 | +from nncf.parameters import ModelType |
| 16 | +import openvino as ov |
| 17 | +import torch |
| 18 | +from transformers import BertForSequenceClassification, BertTokenizer |
| 19 | + |
| 20 | + |
| 21 | +MODEL_DIR = "models" |
| 22 | +os.makedirs(MODEL_DIR, exist_ok=True) |
| 23 | + |
| 24 | +MAX_SEQ_LENGTH = 512 |
| 25 | + |
| 26 | + |
| 27 | +def load_model(inputs, input_info): |
| 28 | + try: |
| 29 | + ir_model_xml = Path(MODEL_DIR) / "bert-base-cased.xml" |
| 30 | + core = ov.Core() |
| 31 | + |
| 32 | + torch_model = BertForSequenceClassification.from_pretrained('bert-base-cased') |
| 33 | + torch_model.eval |
| 34 | + |
| 35 | + # Convert the PyTorch model to OpenVINO IR FP32. |
| 36 | + if not ir_model_xml.exists(): |
| 37 | + model = ov.convert_model(torch_model, example_input=inputs, input=input_info) |
| 38 | + ov.save_model(model, str(ir_model_xml)) |
| 39 | + else: |
| 40 | + model = core.read_model(ir_model_xml) |
| 41 | + |
| 42 | + return model |
| 43 | + except Exception as e: |
| 44 | + print(f"Error in load_model: {e}") |
| 45 | + sys.exit(1) |
| 46 | + |
| 47 | +def create_data_source(): |
| 48 | + try: |
| 49 | + raw_dataset = datasets.load_dataset('glue', 'mrpc', split='validation') |
| 50 | + tokenizer = BertTokenizer.from_pretrained('bert-base-cased') |
| 51 | + |
| 52 | + def _preprocess_fn(examples): |
| 53 | + texts = (examples['sentence1'], examples['sentence2']) |
| 54 | + result = tokenizer(*texts, padding='max_length', max_length=MAX_SEQ_LENGTH, truncation=True) |
| 55 | + result['labels'] = examples['label'] |
| 56 | + return result |
| 57 | + processed_dataset = raw_dataset.map(_preprocess_fn, batched=True, batch_size=1) |
| 58 | + |
| 59 | + return processed_dataset |
| 60 | + except Exception as e: |
| 61 | + print(f"Error in create_data_source: {e}") |
| 62 | + sys.exit(1) |
| 63 | + |
| 64 | +def nncf_quantize(model, inputs): |
| 65 | + try: |
| 66 | + INPUT_NAMES = [key for key in inputs.keys()] |
| 67 | + data_source = create_data_source() |
| 68 | + |
| 69 | + def transform_fn(data_item): |
| 70 | + """ |
| 71 | + Extract the model's input from the data item. |
| 72 | + The data item here is the data item that is returned from the data source per iteration. |
| 73 | + This function should be passed when the data item cannot be used as model's input. |
| 74 | + """ |
| 75 | + inputs = { |
| 76 | + name: np.asarray([data_item[name]], dtype=np.int64) for name in INPUT_NAMES |
| 77 | + } |
| 78 | + return inputs |
| 79 | + |
| 80 | + calibration_dataset = nncf.Dataset(data_source, transform_fn) |
| 81 | + # Quantize the model. By specifying model_type, we specify additional transformer patterns in the model. |
| 82 | + quantized_model = nncf.quantize(model, calibration_dataset, |
| 83 | + model_type=ModelType.TRANSFORMER) |
| 84 | + |
| 85 | + |
| 86 | + compressed_model_xml = Path(MODEL_DIR) / "quantized_bert_base_cased.xml" |
| 87 | + ov.save_model(quantized_model, compressed_model_xml) |
| 88 | + except Exception as e: |
| 89 | + print(f"Error in nncf_quantize: {e}") |
| 90 | + sys.exit(1) |
| 91 | + |
| 92 | +if __name__ == '__main__': |
| 93 | + input_shape = ov.PartialShape([1, 512]) |
| 94 | + input_info = [("input_ids", input_shape, np.int64),("attention_mask", input_shape, np.int64),("token_type_ids", input_shape, np.int64)] |
| 95 | + default_input = torch.ones(1, MAX_SEQ_LENGTH, dtype=torch.int64) |
| 96 | + inputs = { |
| 97 | + "input_ids": default_input, |
| 98 | + "attention_mask": default_input, |
| 99 | + "token_type_ids": default_input, |
| 100 | + } |
| 101 | + |
| 102 | + model = load_model(inputs, input_info) |
| 103 | + quantized_model = nncf_quantize(model, inputs) |
0 commit comments