Closed apoorvu-sharechat closed 2 months ago
Hello @apoorvu-sharechat,
Thank you for your interest in NNCF and for your contributions to improving NNCF.
Unfortunately, NNCF does not support quantization the custom Keras model class yet, only built-in Keras model classes. I mean that in case 2 the basic_model
is skipped during quantization. As workaround, you can rewrite model using Keras model classes.
Anyway, you highlight a bug in the model transformer and I prepared a fix https://github.com/openvinotoolkit/nncf/pull/2750
Thanks @alexsu52 that's good to know. We could probably rewrite our production model to avoid using a custom model class, but we have some custom layers we use for embeddings etc. Will that also be a problem or are models with custom layers at least supported?
May I know if you are going to use post-training quantization and infer the quantized model via OpenVINO? If yes, then I suggest you to convert the model in OpenVINO and then quantize it (docs: https://docs.openvino.ai/2024/openvino-workflow/model-preparation/convert-model-tensorflow.html). This will save you from rewriting the model.
Will that also be a problem or are models with custom layers at least supported?
Custom layers will be skipped during quantization.
Testing showed that #2750 breaks the distribution training, so I closed the PR. The only possible option is to change the model as follows so that it is loaded correctly from Keras config:
@tf.keras.utils.register_keras_serializable()
class BasicModel(tf.keras.Model):
def __init__(self, name, dense_config=None, **kwargs):
super(BasicModel, self).__init__(name=name, **kwargs)
self.name_ = name
self.dense = (
tf.keras.layers.Dense(2) if dense_config is None else tf.keras.layers.Dense.from_config(dense_config)
)
def call(self, inputs):
return self.dense(inputs)
def get_config(self):
config = super().get_config()
config.update(
{
"name": self.name_,
"dense_config": self.dense.get_config(),
}
)
return config
def make_model():
input_layer = tf.keras.Input(shape=(2,))
model = BasicModel(name="basic_model")
output = model(input_layer)
return tf.keras.Model(input_layer, output)
Thanks @alexsu52. I was hoping to quantize the model (post training) and continue using TensorFlow Serving to serve the model.
On that note, even if I don't use a custom model class I still see issues: I was trying to benchmark a simple model with a few Dense layers before and after quantization, and the quantized model seems to perform very poorly:
model = tf.keras.Sequential([
tf.keras.layers.Dense(2000, input_shape=(2,)),
tf.keras.layers.Dense(1000),
tf.keras.layers.Dense(1)
])
inputs = tf.constant([[1, 2]])
model(inputs)
calibration_dataset = tf.data.Dataset.from_tensor_slices(np.array([[1, 2], [3, 4], [5, 6]])).batch(1)
quantized_model = nncf.quantize(model, nncf.Dataset(calibration_dataset))
def run_benchmark(model):
x = tf.constant([[1, 2]])
N = 10
for i in range(N):
y = model(x)
N = 100
times = []
for i in range(N):
t1 = time.time()
y = model(x)
t2 = time.time()
times.append(t2-t1)
p50_time = np.percentile(times, 50) * 1000
print(f"P50 (ms):", p50_time)
run_benchmark(model)
run_benchmark(quantized_model)
Output:
INFO:nncf:Creating compression algorithm: quantization
P50 (ms): 2.215147018432617
P50 (ms): 36.72218322753906
The quantized model is 18x slower than baseline :/ If I look at the layers in the model I can see fake quantization layers like this: dense_19/fake_quantize
.
Do I need to convert the quantized model to OpenVino IR for the quantization to actually work?
Given our model serving is built on TensorFlow Serving we would like to continue using it if possible as migration to OVMS would require some effort.
Yes, you need to convert TensorFlow model to OpenVINO model and compile OpenVINO model to see speed up:
model = tf.keras.Sequential(
[tf.keras.layers.Dense(2000, input_shape=(2,)), tf.keras.layers.Dense(1000), tf.keras.layers.Dense(1)]
)
inputs = tf.constant([[1, 2]])
model(inputs)
calibration_dataset = tf.data.Dataset.from_tensor_slices(np.array([[1, 2], [3, 4], [5, 6]])).batch(1)
quantized_model = nncf.quantize(model, nncf.Dataset(calibration_dataset))
def run_benchmark(model):
x = tf.constant([[1, 2]])
N = 10
for i in range(N):
y = model(x)
N = 100
times = []
for i in range(N):
t1 = time.time()
y = model(x)
t2 = time.time()
times.append(t2 - t1)
p50_time = np.percentile(times, 50) * 1000
print(f"P50 (ms):", p50_time)
run_benchmark(model)
run_benchmark(quantized_model)
ov_model = ov.convert_model(model)
ov_quantized_model = ov.convert_model(quantized_model)
ov_compiled_model = ov.compile_model(ov_model)
ov_compiled_quantized_model = ov.compile_model(ov_quantized_model)
run_benchmark(ov_compiled_model)
run_benchmark(ov_compiled_quantized_model)
Output:
P50 (ms): 1.6291141510009766
P50 (ms): 19.118547439575195
P50 (ms): 0.14448165893554688
P50 (ms): 0.12946128845214844
Quantizing the TensorFlow model makes sense if you plan to use Quantization Aware Training (QAT). Otherwise, it is better to use the OpenVINO model as an input for nncf.quantize()
:
import os
import time
import openvino as ov
# Disable GPUs if any on server as we want to quantize for CPU inference
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import tensorflow as tf
import nncf
model = tf.keras.Sequential(
[tf.keras.layers.Dense(2000, input_shape=(2,)), tf.keras.layers.Dense(1000), tf.keras.layers.Dense(1)]
)
inputs = tf.constant([[1, 2]])
model(inputs)
# convert model
ov_model = ov.convert_model(model)
calibration_dataset = tf.data.Dataset.from_tensor_slices(np.array([[1, 2], [3, 4], [5, 6]])).batch(1)
ov_quantized_model = nncf.quantize(ov_model, nncf.Dataset(calibration_dataset))
def run_benchmark(model):
x = tf.constant([[1, 2]])
N = 10
for i in range(N):
y = model(x)
N = 100
times = []
for i in range(N):
t1 = time.time()
y = model(x)
t2 = time.time()
times.append(t2 - t1)
p50_time = np.percentile(times, 50) * 1000
print(f"P50 (ms):", p50_time)
ov_compiled_model = ov.compile_model(ov_model)
ov_compiled_quantized_model = ov.compile_model(ov_quantized_model)
run_benchmark(model)
run_benchmark(ov_compiled_model)
run_benchmark(ov_compiled_quantized_model)
Thanks a lot @alexsu52 . I'll try converting the our model first and then quantizing.
So there is no way to serve models quantized by NNCF using Tensorflow Serving then?
So there is no way to serve models quantized by NNCF using Tensorflow Serving then?
NNCF does not cover this option. Could you share your motivation? Is this necessary for a smooth transition between TensorFlow Serving and OVMS?
@alexsu52 there are some features that we use in our model that don't seem to be supported in OpenVino. E.g., TF Transform: https://www.tensorflow.org/tfx/tutorials/transform/census#export_the_model. At least it's not very clear if they are supported.
To get the benefits of quantization as soon as possible, I was wondering if it was possible to run the quantized models with TF serving, and since the model output by nncf.quantize was a tf.Module, it looked like that might be possible.
But IIUC the tf.Module returned by the quantize function is a sort of annotated version of the original module to tell openvino how quantization should be done, and so it can't be executed in TF serving.
@apoorvu-sharechat, thanks for your answer!
@alexsu52 there are some features that we use in our model that don't seem to be supported in OpenVino. E.g., TF Transform: https://www.tensorflow.org/tfx/tutorials/transform/census#export_the_model. At least it's not very clear if they are supported.
Take a look at https://docs.openvino.ai/2024/openvino-workflow/running-inference/optimize-inference/optimize-preprocessing.html for information how to optimize preprocessing step using OpenVINO.
To get the benefits of quantization as soon as possible, I was wondering if it was possible to run the quantized models with TF serving, and since the model output by nncf.quantize was a tf.Module, it looked like that might be possible.
But IIUC the tf.Module returned by the quantize function is a sort of annotated version of the original module to tell openvino how quantization should be done, and so it can't be executed in TF serving.
nncf.quantize()
quantizes TensorFlow models using standard TensorFlow operations so called fake-quanitze (https://www.tensorflow.org/api_docs/python/tf/quantization/fake_quant_with_min_max_vars) and returns a quanitzed model which can be infer in "fake-quantize" mode in floating precision. To get performance the quantized model with fake-quantize operations should be converted to OpenVINO
or other backend which support TF fake quantized operations, such as TensorFlow Lite
.
You can try to add the following code to the PTQ TensorFlow example to see speed-up the quantized model in TensorFlow Lite:
tf_quantized_model = nncf.quantize(
tf_model,
calibration_dataset,
advanced_parameters=nncf.AdvancedQuantizationParameters(
activations_quantization_params=QuantizationParameters(per_channel=False)
),
)
converter = tf.lite.TFLiteConverter.from_keras_model(tf_quantized_model)
tflite_model = converter.convert()
tflite_file = "/tmp/quantized_mnist.tflite"
open(tflite_file, "wb").write(tflite_model)
interpreter = tf.lite.Interpreter(model_path=tflite_file)
interpreter.allocate_tensors()
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]
metric = tf.keras.metrics.CategoricalAccuracy(name="acc@1")
for images, labels in tqdm(val_dataset):
interpreter.set_tensor(input_index, tf.cast(images, tf.float32))
interpreter.invoke()
pred = interpreter.get_tensor(output_index)
metric.update_state(labels, pred)
print(metric.result())
Disclaimer: NNCF does not quantize model taking account specific TensorFlow Lite runtime. This may result in suboptimal model inference.
Ok that's very helpful, thanks @alexsu52! I was able to get the basic model above quantized, converted to openvino IR, and running with good performance and minimal quantization error :)
I ran into some further issues trying to convert our production model to openvino IR even without the preprocessing, but will raise an issue against the appropriate repo.
🐛 Describe the bug
I'm trying to use NNCF for a rec sys model to quantize it to int8. Before using it on our production model, I wanted to get it working on a simple toy example first but am seeing some issues.
I tried to do exactly the same type of quantization two different ways, and they gave very different results.
I've repeated this experiment multiple times but the results don't change. Can someone please help me debug why this is happening? The production model we want to quantize uses something like approach 2/, so we are blocked from using NNCF until we can resolve this.
Thanks!
Environment
pip freeze output:
OS info:
Hardware info:
Minimal Reproducible Example
Approach 1/ which gives good results:
Output:
Score before and after match very well.
Approach 2/, which gives very bad results:
Output:
Very large difference in scores.
Repeating exercise several times gives similar results.
Here's a notebook with the two approaches to make repro easier: https://gist.github.com/apoorvu-sharechat/bc3695ead56a98c86518b3dd0a26b5ad
Are you going to submit a PR?