|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Copyright (c) 2022 Intel Corporation |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | +import os |
| 19 | +import tensorflow as tf |
| 20 | +import numpy as np |
| 21 | +from tensorflow import keras |
| 22 | +from tensorflow.keras import layers |
| 23 | +import time |
| 24 | + |
| 25 | +num_classes = 10 |
| 26 | + |
| 27 | +def build_dataset(): |
| 28 | + # Load the data and split it between train and test sets |
| 29 | + (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() |
| 30 | + |
| 31 | + # Scale images to the [0, 1] range |
| 32 | + x_train = x_train.astype("float32") / 255 |
| 33 | + x_test = x_test.astype("float32") / 255 |
| 34 | + # Make sure images have shape (28, 28, 1) |
| 35 | + x_train = np.expand_dims(x_train, -1) |
| 36 | + x_test = np.expand_dims(x_test, -1) |
| 37 | + |
| 38 | + # convert class vectors to binary class matrices |
| 39 | + y_train = keras.utils.to_categorical(y_train, num_classes) |
| 40 | + y_test = keras.utils.to_categorical(y_test, num_classes) |
| 41 | + return x_train, y_train, x_test, y_test |
| 42 | + |
| 43 | +class Dataset(): |
| 44 | + def __init__(self, ): |
| 45 | + _, _ , self.inputs, self.labels = build_dataset() |
| 46 | + |
| 47 | + def __getitem__(self, idx): |
| 48 | + return self.inputs[idx], self.labels[idx] |
| 49 | + |
| 50 | + def __len__(self): |
| 51 | + assert len(self.inputs) == len(self.labels), 'inputs should have equal len with labels' |
| 52 | + return len(self.inputs) |
| 53 | + |
| 54 | +def build_model(x_train, y_train, x_test, y_test): |
| 55 | + if os.path.exists('fp32_model'): |
| 56 | + model = keras.models.load_model('fp32_model') |
| 57 | + return model |
| 58 | + # Model / data parameters |
| 59 | + input_shape = (28, 28, 1) |
| 60 | + model = keras.Sequential( |
| 61 | + [ |
| 62 | + keras.Input(shape=input_shape), |
| 63 | + layers.Conv2D(32, kernel_size=(3, 3), activation="relu"), |
| 64 | + layers.MaxPooling2D(pool_size=(2, 2)), |
| 65 | + layers.Conv2D(64, kernel_size=(3, 3), activation="relu"), |
| 66 | + layers.MaxPooling2D(pool_size=(2, 2)), |
| 67 | + layers.Flatten(), |
| 68 | + layers.Dropout(0.5), |
| 69 | + layers.Dense(num_classes, activation="softmax"), |
| 70 | + ] |
| 71 | + ) |
| 72 | + |
| 73 | + batch_size = 128 |
| 74 | + epochs = 1 |
| 75 | + |
| 76 | + model.compile(loss="categorical_crossentropy", optimizer="adam", |
| 77 | + metrics=["accuracy"], run_eagerly=True) |
| 78 | + model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1) |
| 79 | + model.summary() |
| 80 | + if not os.path.exists('fp32_model'): |
| 81 | + model.save('fp32_model') |
| 82 | + return model |
| 83 | + |
| 84 | +def eval_func(model): |
| 85 | + x_train, y_train, x_test, y_test = build_dataset() |
| 86 | + model.compile(metrics=["accuracy"], run_eagerly=False) |
| 87 | + score = model.evaluate(x_test, y_test) |
| 88 | + return score[1] |
| 89 | + |
| 90 | +def main(): |
| 91 | + x_train, y_train, x_test, y_test = build_dataset() |
| 92 | + model = build_model(x_train, y_train, x_test, y_test) |
| 93 | + |
| 94 | + from neural_compressor.quantization import fit |
| 95 | + from neural_compressor.config import PostTrainingQuantConfig |
| 96 | + from neural_compressor.utils.utility import set_random_seed |
| 97 | + from neural_compressor.experimental import common |
| 98 | + set_random_seed(9527) |
| 99 | + config = PostTrainingQuantConfig(backend='itex') |
| 100 | + quantized_model = fit(model, |
| 101 | + conf=config, |
| 102 | + calib_dataloader=common.DataLoader(Dataset(), batch_size=10), |
| 103 | + eval_func=eval_func) |
| 104 | + |
| 105 | +if __name__ == '__main__': |
| 106 | + main() |
| 107 | + |
0 commit comments