Pruned model doesn't work with multi-gpu
Feature Request: Pruned model isn't working with tensorflow.keras.utils.multi_gpu_model, could you add this support?
Even when sparsity.UpdatePruningStep() is added in the callbacks list, the following error is shown:
tensorflow.python.framework.errors_impl.InvalidArgumentError: 2 root error(s) found.
(0) Invalid argument: assertion failed: [Prune() wrapper requires the UpdatePruningStep callback to be provided during training. Please add it as a callback to your model.fit call.] [Condition x >= y did not hold element-wise:x (replica_1_1/sequential/prune_low_magnitude_conv2d/cond/assert_greater_equal/ReadVariableOp:0) = ] [-1] [y (replica_1_1/sequential/prune_low_magnitude_conv2d/cond/assert_greater_equal/y:0) = ] [0]
[[{{node replica_1_1/sequential/prune_low_magnitude_conv2d/cond/assert_greater_equal/Assert/Assert}}]]
(1) Invalid argument: assertion failed: [Prune() wrapper requires the UpdatePruningStep callback to be provided during training. Please add it as a callback to your model.fit call.] [Condition x >= y did not hold element-wise:x (replica_1_1/sequential/prune_low_magnitude_conv2d/cond/assert_greater_equal/ReadVariableOp:0) = ] [-1] [y (replica_1_1/sequential/prune_low_magnitude_conv2d/cond/assert_greater_equal/y:0) = ] [0]
[[{{node replica_1_1/sequential/prune_low_magnitude_conv2d/cond/assert_greater_equal/Assert/Assert}}]]
[[replica_0_1/sequential/prune_low_magnitude_conv2d/cond/Sub/ReadVariableOp/_1251]]
The code below shows an example of errors thrown for pruned_parallel_model.fit.
#!/usr/bin/env python
# coding: utf-8
# ##### Copied from https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras
import numpy as np
import tempfile
import os
import tensorflow as tf
from tensorflow_model_optimization.sparsity import keras as sparsity
import tensorflow.keras.backend as K
from tensorflow.keras.utils import multi_gpu_model
def main():
K.clear_session()
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
session.run(tf.compat.v1.global_variables_initializer())
session.run(tf.compat.v1.tables_initializer())
K.set_session(session)
# ## Prepare the training data
batch_size = 128
num_classes = 10
epochs = 10
# input image dimensions
img_rows, img_cols = 28, 28
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
if tf.keras.backend.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
# ## Train a MNIST model without pruning
# ### Build the MNIST model
l = tf.keras.layers
model = tf.keras.Sequential([
l.Conv2D(
32, 5, padding='same', activation='relu', input_shape=input_shape),
l.MaxPooling2D((2, 2), (2, 2), padding='same'),
l.BatchNormalization(),
l.Conv2D(64, 5, padding='same', activation='relu'),
l.MaxPooling2D((2, 2), (2, 2), padding='same'),
l.Flatten(),
l.Dense(1024, activation='relu'),
l.Dropout(0.4),
l.Dense(num_classes, activation='softmax')
])
model.summary()
logdir = tempfile.mkdtemp()
print('Writing training logs to ' + logdir)
# ### Train the model to reach an accuracy >99%
callbacks = [tf.keras.callbacks.TensorBoard(log_dir=logdir, profile_batch=0)]
#~ model.compile(
#~ loss=tf.keras.losses.categorical_crossentropy,
#~ optimizer='adam',
#~ metrics=['accuracy'])
parallel_model = multi_gpu_model(model, 2)
parallel_model.compile(
loss=tf.keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy'])
parallel_model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
callbacks=callbacks,
validation_data=(x_test, y_test))
#~ score = model.evaluate(x_test, y_test, verbose=0)
#~ print('Test loss:', score[0])
#~ print('Test accuracy:', score[1])
# ### Save the original model for size comparison later
# Backend agnostic way to save/restore models
_, keras_file = tempfile.mkstemp('.h5')
print('Saving model to: ', keras_file)
tf.keras.models.save_model(model, keras_file, include_optimizer=False)
# ### Prune a whole model
# Load the serialized model
loaded_model = tf.keras.models.load_model(keras_file)
epochs = 4
num_train_samples = x_train.shape[0]
end_step = np.ceil(1.0 * num_train_samples / batch_size).astype(np.int32) * epochs
print('End step: ' + str(end_step))
new_pruning_params = {
'pruning_schedule': sparsity.PolynomialDecay(initial_sparsity=0.50,
final_sparsity=0.90,
begin_step=0,
end_step=end_step,
frequency=100)
}
new_pruned_model = sparsity.prune_low_magnitude(model, **new_pruning_params)
new_pruned_model.summary()
# Add a pruning step callback to peg the pruning step to the optimizer's
# step. Also add a callback to add pruning summaries to tensorboard
callbacks = [
sparsity.UpdatePruningStep(),
sparsity.PruningSummaries(log_dir=logdir, profile_batch=0)
]
for i in range(2):
if i:
cur_model = multi_gpu_model(new_pruned_model, 2)
else:
cur_model = tf.keras.models.clone_model(new_pruned_model)
cur_model.compile(
loss=tf.keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy'])
cur_model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
callbacks=callbacks,
validation_data=(x_test, y_test))
print("i", i, "ran successfully")
'''
Throws errors for multi_gpu_model (when i=1):
Invalid argument: assertion failed: [Prune() wrapper requires the UpdatePruningStep callback to be provided during training.
Please add it as a callback to your model.fit call.]
'''
#~ score = new_pruned_model.evaluate(x_test, y_test, verbose=0)
#~ print('Test loss:', score[0])
#~ print('Test accuracy:', score[1])
if __name__ == "__main__":
main()
same for me
I had similar problems when I tried to cast a tensorflow.keras model to tensorflow_model_optimization.sparsity.keras
I now believe the point is to build your model immediately in tensorflow_model_optimization.sparsity.keras and maybe strip the pruning properties later with
final_model = sparsity.strip_pruning(pruned_model)
So I suggest you build your model like this:
model = tf.keras.Sequential([
sparsity.prune_low_magnitude(l.Conv2D(
32, 5, padding='same', activation='relu', input_shape=input_shape),**pruning_params),
l.MaxPooling2D((2, 2), (2, 2), padding='same'),
l.BatchNormalization(),
sparsity.prune_low_magnitude(l.Conv2D(64, 5, padding='same', activation='relu'),**pruning_params),
l.MaxPooling2D((2, 2), (2, 2), padding='same'),
l.Flatten(),
sparsity.prune_low_magnitude(l.Dense(1024, activation='relu'),**pruning_params),
l.Dropout(0.4),
sparsity.prune_low_magnitude(l.Dense(num_classes, activation='softmax'),**pruning_params)
])
As suggested, this has been deprecated in favor of tf.distribute, which we support (see our compatibility matrix).
Closing and please feel free to file issues regarding tf.distribute usage with mot.