Skip to content

Commit 1d0d565

Browse files
ClarkChin08lvliang-intelchensuyue
authored andcommitted
add keras-in/keras-out to INC (#243)
Signed-off-by: Lv, Liang1 <[email protected]> Signed-off-by: chensuyue <[email protected]> Co-authored-by: Lv, Liang1 <[email protected]> Co-authored-by: chensuyue <[email protected]> Signed-off-by: zehao-intel <[email protected]>
1 parent 7f47ef6 commit 1d0d565

File tree

20 files changed

+1386
-66
lines changed

20 files changed

+1386
-66
lines changed

.azure-pipelines/scripts/ut/env_setup.sh

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ elif [[ "${tensorflow_version}" != "" ]]; then
2828
pip install intel-tensorflow==${tensorflow_version}
2929
fi
3030

31-
if [[ "${itex_version}" != "" ]]; then
31+
if [[ "${itex_version}" == "nightly" ]]; then
32+
pip install /tf_dataset/itex_binary/221209/intel_extension_for_tensorflow-1.1.0-cp38-cp38-linux_x86_64.whl
33+
pip install /tf_dataset/itex_binary/221209/intel_extension_for_tensorflow_lib-1.1.0.0-cp38-cp38-linux_x86_64.whl
34+
elif [[ "${itex_version}" != "" ]]; then
3235
pip install --upgrade intel-extension-for-tensorflow[cpu]==${itex_version}
3336
fi
3437

.azure-pipelines/scripts/ut/run_basic_itex.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ python -c "import neural_compressor as nc;print(nc.version.__version__)"
33
echo "run basic itex"
44

55
echo "specify fwk version..."
6-
export itex_version='1.0.0'
6+
export itex_version='nightly'
77
export tensorflow_version='2.10.0-official'
88

99
echo "set up UT env..."

examples/keras/mnist/README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Step-by-Step
2+
============
3+
4+
This document list steps of reproducing Keras mnist model tuning results via Neural Compressor.
5+
This example can run on Intel CPUs.
6+
7+
# Prerequisite
8+
9+
### 1. Installation
10+
Recommend python 3.6 or higher version.
11+
12+
```shell
13+
# Install Intel® Neural Compressor
14+
pip install neural-compressor
15+
```
16+
17+
### 2. Install Tensorflow
18+
```shell
19+
pip install tensorflow
20+
```
21+
> Note: Supported Tensorflow version > 2.10.0.
22+
23+
### 3. Installation Dependency packages
24+
```shell
25+
cd examples/keras/mnist/
26+
pip install -r requirements.txt
27+
```
28+
29+
#### Quantizing the model on Intel CPU(Experimental)
30+
Intel Extension for Tensorflow for Intel CPUs is experimental currently. It's not mandatory for quantizing the model on Intel CPUs.
31+
32+
```shell
33+
pip install --upgrade intel-extension-for-tensorflow[cpu]
34+
```
35+
36+
# Run
37+
38+
```shell
39+
cd examples/keras/mnist/
40+
python mnist.py
41+
```

examples/keras/mnist/mnist.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
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+
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
tensorflow
2+
neural-compressor
3+
intel-extension-for-tensorflow[cpu]

0 commit comments

Comments
 (0)