Sparsity and cluster preserving quantization aware training (PCQAT) Keras example

View on TensorFlow.org Run in Google Colab View on GitHub Download notebook

Overview

This is an end to end example showing the usage of the sparsity and cluster preserving quantization aware training (PCQAT) API, part of the TensorFlow Model Optimization Toolkit's collaborative optimization pipeline.

Other pages

For an introduction to the pipeline and other available techniques, see the collaborative optimization overview page.

Contents

In the tutorial, you will:

  1. Train a tf.keras model for the MNIST dataset from scratch.
  2. Fine-tune the model with pruning and see the accuracy and observe that the model was successfully pruned.
  3. Apply sparsity preserving clustering on the pruned model and observe that the sparsity applied earlier has been preserved.
  4. Apply QAT and observe the loss of sparsity and clusters.
  5. Apply PCQAT and observe that both sparsity and clustering applied earlier have been preserved.
  6. Generate a TFLite model and observe the effects of applying PCQAT on it.
  7. Compare the sizes of the different models to observe the compression benefits of applying sparsity followed by the collaborative optimization techniques of sparsity preserving clustering and PCQAT.
  8. Compare the accurracy of the fully optimized model with the un-optimized baseline model accuracy.

Setup

You can run this Jupyter Notebook in your local virtualenv or colab. For details of setting up dependencies, please refer to the installation guide.

 pip install -q tensorflow-model-optimization
import tensorflow as tf

import numpy as np
import tempfile
import zipfile
import os

Train a tf.keras model for MNIST to be pruned and clustered

# Load MNIST dataset
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
test_images  = test_images / 255.0

model = tf.keras.Sequential([
  tf.keras.layers.InputLayer(input_shape=(28, 28)),
  tf.keras.layers.Reshape(target_shape=(28, 28, 1)),
  tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3),
                         activation=tf.nn.relu),
  tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(10)
])

opt = tf.keras.optimizers.Adam(learning_rate=1e-3)

# Train the digit classification model
model.compile(optimizer=opt,
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(
    train_images,
    train_labels,
    validation_split=0.1,
    epochs=10
)
2023-05-26 11:36:17.624469: E tensorflow/compiler/xla/stream_executor/cuda/cuda_driver.cc:268] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected
Epoch 1/10
1688/1688 [==============================] - 8s 4ms/step - loss: 0.3262 - accuracy: 0.9074 - val_loss: 0.1355 - val_accuracy: 0.9653
Epoch 2/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.1227 - accuracy: 0.9646 - val_loss: 0.0826 - val_accuracy: 0.9792
Epoch 3/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0825 - accuracy: 0.9764 - val_loss: 0.0721 - val_accuracy: 0.9792
Epoch 4/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0684 - accuracy: 0.9802 - val_loss: 0.0712 - val_accuracy: 0.9785
Epoch 5/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0601 - accuracy: 0.9817 - val_loss: 0.0579 - val_accuracy: 0.9833
Epoch 6/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0532 - accuracy: 0.9836 - val_loss: 0.0612 - val_accuracy: 0.9832
Epoch 7/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0490 - accuracy: 0.9844 - val_loss: 0.0592 - val_accuracy: 0.9828
Epoch 8/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0439 - accuracy: 0.9870 - val_loss: 0.0634 - val_accuracy: 0.9817
Epoch 9/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0400 - accuracy: 0.9878 - val_loss: 0.0594 - val_accuracy: 0.9825
Epoch 10/10
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0367 - accuracy: 0.9889 - val_loss: 0.0713 - val_accuracy: 0.9817
<keras.src.callbacks.History at 0x7f6a865108b0>

Evaluate the baseline model and save it for later usage

_, baseline_model_accuracy = model.evaluate(
    test_images, test_labels, verbose=0)

print('Baseline test accuracy:', baseline_model_accuracy)

_, keras_file = tempfile.mkstemp('.h5')
print('Saving model to: ', keras_file)
tf.keras.models.save_model(model, keras_file, include_optimizer=False)
Baseline test accuracy: 0.9789999723434448
Saving model to:  /tmpfs/tmp/tmpyjt8tnp4.h5
/tmpfs/tmp/ipykernel_36753/1025833175.py:8: UserWarning: You are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')`.
  tf.keras.models.save_model(model, keras_file, include_optimizer=False)

Prune and fine-tune the model to 50% sparsity

Apply the prune_low_magnitude() API to achieve the pruned model that is to be clustered in the next step. Refer to the pruning comprehensive guide for more information on the pruning API.

Define the model and apply the sparsity API

Note that the pre-trained model is used.

import tensorflow_model_optimization as tfmot

prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude

pruning_params = {
      'pruning_schedule': tfmot.sparsity.keras.ConstantSparsity(0.5, begin_step=0, frequency=100)
  }

callbacks = [
  tfmot.sparsity.keras.UpdatePruningStep()
]

pruned_model = prune_low_magnitude(model, **pruning_params)

# Use smaller learning rate for fine-tuning
opt = tf.keras.optimizers.Adam(learning_rate=1e-5)

pruned_model.compile(
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
  optimizer=opt,
  metrics=['accuracy'])

Fine-tune the model, check sparsity, and evaluate the accuracy against baseline

Fine-tune the model with pruning for 3 epochs.

# Fine-tune model
pruned_model.fit(
  train_images,
  train_labels,
  epochs=3,
  validation_split=0.1,
  callbacks=callbacks)
Epoch 1/3
1688/1688 [==============================] - 9s 4ms/step - loss: 0.0717 - accuracy: 0.9755 - val_loss: 0.0858 - val_accuracy: 0.9752
Epoch 2/3
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0572 - accuracy: 0.9820 - val_loss: 0.0772 - val_accuracy: 0.9782
Epoch 3/3
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0514 - accuracy: 0.9842 - val_loss: 0.0732 - val_accuracy: 0.9790
<keras.src.callbacks.History at 0x7f6a86b655b0>

Define helper functions to calculate and print the sparsity and clusters of the model.

def print_model_weights_sparsity(model):
    for layer in model.layers:
        if isinstance(layer, tf.keras.layers.Wrapper):
            weights = layer.trainable_weights
        else:
            weights = layer.weights
        for weight in weights:
            if "kernel" not in weight.name or "centroid" in weight.name:
                continue
            weight_size = weight.numpy().size
            zero_num = np.count_nonzero(weight == 0)
            print(
                f"{weight.name}: {zero_num/weight_size:.2%} sparsity ",
                f"({zero_num}/{weight_size})",
            )

def print_model_weight_clusters(model):
    for layer in model.layers:
        if isinstance(layer, tf.keras.layers.Wrapper):
            weights = layer.trainable_weights
        else:
            weights = layer.weights
        for weight in weights:
            # ignore auxiliary quantization weights
            if "quantize_layer" in weight.name:
                continue
            if "kernel" in weight.name:
                unique_count = len(np.unique(weight))
                print(
                    f"{layer.name}/{weight.name}: {unique_count} clusters "
                )

Let's strip the pruning wrapper first, then check that the model kernels were correctly pruned.

stripped_pruned_model = tfmot.sparsity.keras.strip_pruning(pruned_model)

print_model_weights_sparsity(stripped_pruned_model)
conv2d/kernel:0: 50.00% sparsity  (54/108)
dense/kernel:0: 50.00% sparsity  (10140/20280)

Apply sparsity preserving clustering and check its effect on model sparsity in both cases

Next, apply sparsity preserving clustering on the pruned model and observe the number of clusters and check that the sparsity is preserved.

import tensorflow_model_optimization as tfmot
from tensorflow_model_optimization.python.core.clustering.keras.experimental import (
    cluster,
)

cluster_weights = tfmot.clustering.keras.cluster_weights
CentroidInitialization = tfmot.clustering.keras.CentroidInitialization

cluster_weights = cluster.cluster_weights

clustering_params = {
  'number_of_clusters': 8,
  'cluster_centroids_init': CentroidInitialization.KMEANS_PLUS_PLUS,
  'preserve_sparsity': True
}

sparsity_clustered_model = cluster_weights(stripped_pruned_model, **clustering_params)

sparsity_clustered_model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

print('Train sparsity preserving clustering model:')
sparsity_clustered_model.fit(train_images, train_labels,epochs=3, validation_split=0.1)
Train sparsity preserving clustering model:
Epoch 1/3
1688/1688 [==============================] - 8s 5ms/step - loss: 0.0456 - accuracy: 0.9860 - val_loss: 0.0699 - val_accuracy: 0.9805
Epoch 2/3
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0438 - accuracy: 0.9864 - val_loss: 0.0694 - val_accuracy: 0.9805
Epoch 3/3
1688/1688 [==============================] - 7s 4ms/step - loss: 0.0436 - accuracy: 0.9862 - val_loss: 0.0607 - val_accuracy: 0.9842
<keras.src.callbacks.History at 0x7f6a866a4af0>

Strip the clustering wrapper first, then check that the model is correctly pruned and clustered.

stripped_clustered_model = tfmot.clustering.keras.strip_clustering(sparsity_clustered_model)

print("Model sparsity:\n")
print_model_weights_sparsity(stripped_clustered_model)

print("\nModel clusters:\n")
print_model_weight_clusters(stripped_clustered_model)
Model sparsity:

kernel:0: 50.00% sparsity  (54/108)
kernel:0: 57.53% sparsity  (11668/20280)

Model clusters:

conv2d/kernel:0: 8 clusters 
dense/kernel:0: 8 clusters

Apply QAT and PCQAT and check effect on model clusters and sparsity

Next, apply both QAT and PCQAT on the sparse clustered model and observe that PCQAT preserves weight sparsity and clusters in your model. Note that the stripped model is passed to the QAT and PCQAT API.

# QAT
qat_model = tfmot.quantization.keras.quantize_model(stripped_clustered_model)

qat_model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
print('Train qat model:')
qat_model.fit(train_images, train_labels, batch_size=128, epochs=1, validation_split=0.1)

# PCQAT
quant_aware_annotate_model = tfmot.quantization.keras.quantize_annotate_model(
              stripped_clustered_model)
pcqat_model = tfmot.quantization.keras.quantize_apply(
              quant_aware_annotate_model,
              tfmot.experimental.combine.Default8BitClusterPreserveQuantizeScheme(preserve_sparsity=True))

pcqat_model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
print('Train pcqat model:')
pcqat_model.fit(train_images, train_labels, batch_size=128, epochs=1, validation_split=0.1)
Train qat model:
422/422 [==============================] - 3s 7ms/step - loss: 0.0343 - accuracy: 0.9893 - val_loss: 0.0610 - val_accuracy: 0.9837
Train pcqat model:
WARNING:tensorflow:Gradients do not exist for variables ['conv2d/kernel:0', 'dense/kernel:0'] when minimizing the loss. If you're using `model.compile()`, did you forget to provide a `loss` argument?
WARNING:tensorflow:Gradients do not exist for variables ['conv2d/kernel:0', 'dense/kernel:0'] when minimizing the loss. If you're using `model.compile()`, did you forget to provide a `loss` argument?
WARNING:tensorflow:Gradients do not exist for variables ['conv2d/kernel:0', 'dense/kernel:0'] when minimizing the loss. If you're using `model.compile()`, did you forget to provide a `loss` argument?
WARNING:tensorflow:Gradients do not exist for variables ['conv2d/kernel:0', 'dense/kernel:0'] when minimizing the loss. If you're using `model.compile()`, did you forget to provide a `loss` argument?
422/422 [==============================] - 4s 7ms/step - loss: 0.0342 - accuracy: 0.9894 - val_loss: 0.0616 - val_accuracy: 0.9837
<keras.src.callbacks.History at 0x7f6a866e2610>
print("QAT Model clusters:")
print_model_weight_clusters(qat_model)
print("\nQAT Model sparsity:")
print_model_weights_sparsity(qat_model)
print("\nPCQAT Model clusters:")
print_model_weight_clusters(pcqat_model)
print("\nPCQAT Model sparsity:")
print_model_weights_sparsity(pcqat_model)
QAT Model clusters:
quant_conv2d/conv2d/kernel:0: 92 clusters 
quant_dense/dense/kernel:0: 16614 clusters 

QAT Model sparsity:
conv2d/kernel:0: 14.81% sparsity  (16/108)
dense/kernel:0: 12.71% sparsity  (2577/20280)

PCQAT Model clusters:
quant_conv2d/conv2d/kernel:0: 8 clusters 
quant_dense/dense/kernel:0: 8 clusters 

PCQAT Model sparsity:
conv2d/kernel:0: 50.00% sparsity  (54/108)
dense/kernel:0: 57.53% sparsity  (11668/20280)

See compression benefits of PCQAT model

Define helper function to get zipped model file.

def get_gzipped_model_size(file):
  # It returns the size of the gzipped model in kilobytes.

  _, zipped_file = tempfile.mkstemp('.zip')
  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:
    f.write(file)

  return os.path.getsize(zipped_file)/1000

Observe that applying sparsity, clustering and PCQAT to a model yields significant compression benefits.

# QAT model
converter = tf.lite.TFLiteConverter.from_keras_model(qat_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
qat_tflite_model = converter.convert()
qat_model_file = 'qat_model.tflite'
# Save the model.
with open(qat_model_file, 'wb') as f:
    f.write(qat_tflite_model)

# PCQAT model
converter = tf.lite.TFLiteConverter.from_keras_model(pcqat_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
pcqat_tflite_model = converter.convert()
pcqat_model_file = 'pcqat_model.tflite'
# Save the model.
with open(pcqat_model_file, 'wb') as f:
    f.write(pcqat_tflite_model)

print("QAT model size: ", get_gzipped_model_size(qat_model_file), ' KB')
print("PCQAT model size: ", get_gzipped_model_size(pcqat_model_file), ' KB')
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp51bhxv1h/assets
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp51bhxv1h/assets
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/lite/python/convert.py:887: UserWarning: Statistics for quantized inputs were expected, but not specified; continuing anyway.
  warnings.warn(
2023-05-26 11:38:27.458701: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:364] Ignored output_format.
2023-05-26 11:38:27.458740: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:367] Ignored drop_control_dependency.
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpxrwt5r_j/assets
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpxrwt5r_j/assets
QAT model size:  14.139  KB
PCQAT model size:  7.758  KB
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/lite/python/convert.py:887: UserWarning: Statistics for quantized inputs were expected, but not specified; continuing anyway.
  warnings.warn(
2023-05-26 11:38:29.642029: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:364] Ignored output_format.
2023-05-26 11:38:29.642066: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:367] Ignored drop_control_dependency.

See the persistence of accuracy from TF to TFLite

Define a helper function to evaluate the TFLite model on the test dataset.

def eval_model(interpreter):
  input_index = interpreter.get_input_details()[0]["index"]
  output_index = interpreter.get_output_details()[0]["index"]

  # Run predictions on every image in the "test" dataset.
  prediction_digits = []
  for i, test_image in enumerate(test_images):
    if i % 1000 == 0:
      print(f"Evaluated on {i} results so far.")
    # Pre-processing: add batch dimension and convert to float32 to match with
    # the model's input data format.
    test_image = np.expand_dims(test_image, axis=0).astype(np.float32)
    interpreter.set_tensor(input_index, test_image)

    # Run inference.
    interpreter.invoke()

    # Post-processing: remove batch dimension and find the digit with highest
    # probability.
    output = interpreter.tensor(output_index)
    digit = np.argmax(output()[0])
    prediction_digits.append(digit)

  print('\n')
  # Compare prediction results with ground truth labels to calculate accuracy.
  prediction_digits = np.array(prediction_digits)
  accuracy = (prediction_digits == test_labels).mean()
  return accuracy

Evaluate the model, which has been pruned, clustered and quantized, and then see that the accuracy from TensorFlow persists in the TFLite backend.

interpreter = tf.lite.Interpreter(pcqat_model_file)
interpreter.allocate_tensors()

pcqat_test_accuracy = eval_model(interpreter)

print('Pruned, clustered and quantized TFLite test_accuracy:', pcqat_test_accuracy)
print('Baseline TF test accuracy:', baseline_model_accuracy)
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
Evaluated on 0 results so far.
Evaluated on 1000 results so far.
Evaluated on 2000 results so far.
Evaluated on 3000 results so far.
Evaluated on 4000 results so far.
Evaluated on 5000 results so far.
Evaluated on 6000 results so far.
Evaluated on 7000 results so far.
Evaluated on 8000 results so far.
Evaluated on 9000 results so far.


Pruned, clustered and quantized TFLite test_accuracy: 0.9803
Baseline TF test accuracy: 0.9789999723434448

Conclusion

In this tutorial, you learned how to create a model, prune it using the prune_low_magnitude() API, and apply sparsity preserving clustering using the cluster_weights() API to preserve sparsity while clustering the weights.

Next, sparsity and cluster preserving quantization aware training (PCQAT) was applied to preserve model sparsity and clusters while using QAT. The final PCQAT model was compared to the QAT one to show that sparsity and clusters are preserved in the former and lost in the latter.

Next, the models were converted to TFLite to show the compression benefits of chaining sparsity, clustering, and PCQAT model optimization techniques and the TFLite model was evaluated to ensure that the accuracy persists in the TFLite backend.

Finally, the PCQAT TFLite model accuracy was compared to the pre-optimization baseline model accuracy to show that collaborative optimization techniques managed to achieve the compression benefits while maintaining a similar accuracy compared to the original model.