model-optimization icon indicating copy to clipboard operation
model-optimization copied to clipboard

Weight name conflicts when keras model consists of subclassed layer

Open kalaluthien opened this issue 6 years ago • 7 comments

Describe the bug Weight name duplication issues when using subclassed keras layer with many ops. For instance, a custom layer with 1Conv+1Dense. (no custom kernel)

System information

TensorFlow installed from (source or binary): binary (pip install tensorflow-gpu)

TensorFlow version: 2.1.0

TensorFlow Model Optimization version: master (built from source)

Python version: 3.7

Describe the expected behavior Annotate each weight in subclassed layer correctly.

Describe the current behavior

  1. When quantize layer, tfmot clones original layer.
class ModelTransformer(object):
  def _get_keras_layer_weights(self, keras_layer):
    """Returns a map of weight name, weight matrix. Keeps keras ordering."""
    weights_map = collections.OrderedDict()
    for weight_tensor, weight_numpy in \
        zip(keras_layer.weights, keras_layer.get_weights()):
      weights_map[self._weight_name(weight_tensor.name)] = weight_numpy

    return weights_map

Because self._weight_name(...) function get rid of layer name information, it leaves only kernel:N or bias:N. If cloned layer is subclassed layer and has many weights like 'mylayer/conv2d/kernel:0' and 'mylayer/dense/kernel:0', names conflict!

  1. When using built-in QuantizeConfigs (e.g. LastValQuantizeConfig), It adds weights with postfix (_min and _max) to original weight name.
class QuantizeWrapper(tf.keras.layers.Wrapper):
  def build(self, input_shape):
    super(QuantizeWrapper, self).build(input_shape)

    self.optimizer_step = self.add_weight(
        'optimizer_step',
        initializer=tf.keras.initializers.Constant(-1),
        dtype=tf.dtypes.int32,
        trainable=False)

    self._weight_vars = []
    for weight, quantizer in \
        self.quantize_config.get_weights_and_quantizers(self.layer):
      quantizer_vars = quantizer.build(weight.shape,
                                       self._weight_name(weight.name), self)

Because self._weight_name(...) function get rid of layer name information, it leaves only kernel:N or bias:N. If cloned layer is subclassed layer and has many weights like 'mylayer/conv2d/kernel:0' and 'mylayer/dense/kernel:0' becomes 'kernel:0'. and min/max weights all become 'kernel_min:0' and 'kernel_max:0'. Names conflict!

Code to reproduce the issue This code is my subclassed layer version of Mnist.

from typing import Any, Dict, List, Optional, Tuple

# for model construction
import tensorflow as tf

# for model quantization
from tensorflow_model_optimization.python.core.quantization.keras import quantize_config
from tensorflow_model_optimization.python.core.quantization.keras import quantizers


class MnistNet(tf.keras.layers.Layer):

    def __init__(self, num_classes: int, **kwargs: Any):
        super().__init__(**kwargs)
        self.num_classes = num_classes

    def get_config(self) -> Dict[str, Any]:
        config = super().get_config()
        config.update({
            'num_classes': self.num_classes,
        })
        return config

    def build(self, input_shape: Any) -> None:
        self.conv1 = tf.keras.layers.Conv2D(
            32, 5,
            padding='same',
            activation='relu',
            use_bias=False,
            input_shape=input_shape,
        )
        self.pool1 = tf.keras.layers.MaxPooling2D((2, 2), (2, 2), padding='same')
        self.conv2 = tf.keras.layers.Conv2D(
            64, 5,
            padding='same',
            activation='relu',
            use_bias=False,
        )
        self.pool2 = tf.keras.layers.MaxPooling2D((2, 2), (2, 2), padding='same')
        self.flatten = tf.keras.layers.Flatten()
        self.fc1 = tf.keras.layers.Dense(1024, activation='relu')
        self.dropout = tf.keras.layers.Dropout(0.4)
        self.fc2 = tf.keras.layers.Dense(self.num_classes)
        self.softmax = tf.keras.layers.Softmax()

    def call(
            self,
            inputs: tf.Tensor,
            training: Optional[bool] = None
    ) -> Tuple[tf.Tensor, Dict[str, Any]]:
        if training is None:
            training = tf.keras.backend.learning_phase()
        x = self.conv1(inputs, training=training)  # -> 28 x 28 x 32
        x = self.pool1(x, training=training)  # -> 14 x 14 x 32
        x = self.conv2(x, training=training)  # -> 14 x 14 x 64
        x = self.pool2(x, training=training)  # -> 7 x 7 x 64
        x = self.flatten(x, training=training)  # -> 3136
        x = self.fc1(x, training=training)  # -> 1024
        x = self.dropout(x, training=training)  # -> 1024
        x = self.fc2(x, training=training)  # -> 10
        x = self.softmax(x, training=training)  # -> 10
        return x, {}


class MnistNetQuantizeConfig(quantize_config.QuantizeConfig):

    def __init__(self):
        self.sublayers_to_be_quantized = [
            'conv1', 'conv2', 'fc1', 'fc2'
        ]

    def get_weights_and_quantizers(self, layer):
        return [
            (sublayer.kernel, MnistNetQuantizer(sublayer.name))
            for name in self.sublayers_to_be_quantized
            for sublayer in [getattr(layer, name)]
        ]

    def get_activations_and_quantizers(self, layer):
        return [
            (sublayer.activation, MnistNetQuantizer(sublayer.name))
            for name in self.sublayers_to_be_quantized
            for sublayer in [getattr(layer, name)]
        ]

    def set_quantize_weights(self, layer, quantize_weights):
        pass

    def set_quantize_activations(self, layer, quantize_activations):
        pass

    def get_output_quantizers(self, layer):
        return []

    def get_config(self) -> Dict[str, Any]:
        return {}


# Fixed version of LastValQauntizer
class MnistNetQuantizer(quantizers.Quantizer):

    def __init__(
            self,
            layer_name: str,
            num_bits: int = 8,
            per_channel: bool = False,
            symmetric: bool = False,
            narrow_range: bool = False,
            initial_min: float = -1.0,
            initial_max: float = +1.0,
    ):
        self.layer_name = layer_name
        self.num_bits = num_bits
        self.per_channel = per_channel
        self.symmetric = symmetric
        self.narrow_range = narrow_range
        self.initial_min = initial_min
        self.initial_max = initial_max

    def get_config(self) -> Dict[str, Any]:
        return {
            'layer_name': self.layer_name,
            'num_bits': self.num_bits,
            'per_channel': self.per_channel,
            'symmetric': self.symmetric,
            'narrow_range': self.narrow_range,
            'initial_min': self.initial_min,
            'initial_max': self.initial_max,
        }

    def build(
            self,
            tensor_shape: Any,
            name: str,
            layer: tf.keras.layers.Layer,
    ) -> Dict[str, Any]:
        # Push front layer_name to weight name,
        # becuase tfmot passes 'splited' weight name,
        # and duplicated name issuses occur.
        # It makes subclassed keras layer cannot use built-in LastValueQuantizer.
        min_var = layer.add_weight(
            self.layer_name + '/' + name + '_min',
            initializer=tf.keras.initializers.Constant(self.initial_min),
            trainable=False,
        )
        max_var = layer.add_weight(
            self.layer_name + '/' + name + '_max',
            initializer=tf.keras.initializers.Constant(self.initial_max),
            trainable=False,
        )
        return {'min_var': min_var, 'max_var': max_var}

    def __call__(self, inputs, step, training, **kwargs):
        with tf.name_scope('MnistNetQuantization'):
            min_var = kwargs['min_var']
            max_var = kwargs['max_var']
            input_shape = inputs.get_shape()
            input_dim = len(input_shape)

            if not training:
                if self.per_channel:
                    assert len(min_var.get_shape()) == 1
                    assert len(max_var.get_shape()) == 1
                    return tf.quantization.fake_quant_with_min_max_vars_per_channel(
                        inputs, min_var, max_var,
                        num_bits=self.num_bits,
                        narrow_range=self.narrow_range,
                    )
                else:
                    assert min_var.get_shape() == []
                    assert max_var.get_shape() == []
                    return tf.quantization.fake_quant_with_min_max_vars(
                        inputs, min_var, max_var,
                        num_bits=self.num_bits,
                        narrow_range=self.narrow_range
                    )

            if self.per_channel:
                if input_dim == 2:
                    reduce_dims = [0]
                elif input_dim == 4:
                    reduce_dims = [0, 1, 2]

            if self.per_channel:
                if input_dim >= 2:
                    batch_min = tf.math.reduce_min(
                        inputs, axis=reduce_dims, name='BatchMin'
                    )
                else:
                    batch_min = inputs
            else:
                batch_min = tf.math.reduce_min(inputs, name='BatchMin')

            if self.per_channel:
                if input_dim >= 2:
                    batch_max = tf.math.reduce_max(
                        inputs, axis=reduce_dims, name='BatchMax')
                else:
                    batch_max = inputs
            else:
                batch_max = tf.math.reduce_max(inputs, name='BatchMax')

            if self.symmetric:
                if self.narrow_range:
                    min_max_ratio = -1
                else:
                    min_max_ratio = -((1 << self.num_bits) - 2) / (1 << self.num_bits)

                range_min = tf.math.minimum(batch_min, batch_max / min_max_ratio)
                range_max = tf.math.maximum(batch_max, batch_min * min_max_ratio)
            else:
                range_min = tf.math.minimum(batch_min, 0.0)
                range_max = tf.math.maximum(batch_max, 0.0)

            assign_min = tf.compat.v1.assign(min_var, range_min, name='AssignMinLast')
            assign_max = tf.compat.v1.assign(max_var, range_max, name='AssignMaxLast')

            if self.per_channel:
                assert len(assign_min.get_shape()) == 1
                assert len(assign_max.get_shape()) == 1
                return tf.quantization.fake_quant_with_min_max_vars_per_channel(
                    inputs, min_var, max_var,
                    num_bits=self.num_bits,
                    narrow_range=self.narrow_range,
                )
            else:
                assert assign_min.get_shape() == []
                assert assign_max.get_shape() == []
                return tf.quantization.fake_quant_with_min_max_vars(
                    inputs, min_var, max_var,
                    num_bits=self.num_bits,
                    narrow_range=self.narrow_range
                )

I lift this layer into keras functional model like:

inputs = tf.keras.Input(
    shape=input_shape,
    batch_size=None,
    dtype=tf.dtypes.float32,
)
annotated_net = quantize_annotate_layer(
    MnistNet(num_classes),
    quantize_config=MnistNetQuantizeConfig(),
)
outputs, _ = annotated_net(inputs)
model_custom = tf.keras.Model(inputs=inputs, outputs=outputs, name='MnistCustom')

Screenshots If applicable, add screenshots to help explain your problem.

Additional context Add any other context about the problem here.

kalaluthien avatar Mar 27 '20 02:03 kalaluthien

Hi @kalaluthien,

Thanks a lot for the detailed report. This is very helpful in reproducing the issue.

The removal of layer name from weights was done since new weights get created with augmented layer names (dense_2 instead of dense_1). This causes the weight names to not match when storing the values after graph transformations. However, you rightly point out, that this fails in cases where a layer contains multiple layers which may have the same weight name. I'll work on a fix for this. Our test set did not include a layer with multiple weights of the same name.

This is a similar issue. I'll work on a fix for it and let you know once it's out.

Thanks once again for the feedback!

nutsiepully avatar Apr 02 '20 08:04 nutsiepully

same problem appears when a model contains another model. When you query the inner model for its weights and pass them through the name processor, you get a shape mismatch because the names of different layers weights are equal.

The problem is evident simply applying default quantization to the tensorflow segmentation example

Traceback (most recent call last):
  File "C:/Users/Alessandro/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_2.py", line 133, in <module>
    model = unet_model(OUTPUT_CHANNELS)
  File "C:/Users/Alessandro/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_2.py", line 130, in unet_model
    return quantize_apply(tf.keras.Model(inputs=inputs, outputs=x))
  File "C:\Users\Alessandro\AppData\Roaming\Python\Python37\site-packages\tensorflow_model_optimization\python\core\quantization\keras\quantize.py", line 402, in quantize_apply
    transformed_model, layer_quantize_map = quantize_transform.apply(unwrapped_model, layer_quantize_map)
  File "C:\Users\Alessandro\AppData\Roaming\Python\Python37\site-packages\tensorflow_model_optimization\python\core\quantization\keras\default_8bit\default_8bit_quantize_layout_transform.py", line 65, in apply
    return model_transformer.ModelTransformer(model, transforms, layer_quantize_map.keys(), layer_quantize_map).transform()
  File "C:\Users\Alessandro\AppData\Roaming\Python\Python37\site-packages\tensorflow_model_optimization\python\core\quantization\keras\graph_transformations\model_transformer.py", line 561, in transform
    self._set_layer_weights(layer, weights)
  File "C:\Users\Alessandro\AppData\Roaming\Python\Python37\site-packages\tensorflow_model_optimization\python\core\quantization\keras\graph_transformations\model_transformer.py", line 445, in _set_layer_weights
    K.batch_set_value(weight_value_tuples)
  File "C:\Users\Alessandro\.conda\envs\keras\lib\site-packages\tensorflow_core\python\keras\backend.py", line 3324, in batch_set_value
    x.assign(np.asarray(value, dtype=dtype(x)))
  File "C:\Users\Alessandro\.conda\envs\keras\lib\site-packages\tensorflow_core\python\ops\resource_variable_ops.py", line 822, in assign
    raise e
  File "C:\Users\Alessandro\.conda\envs\keras\lib\site-packages\tensorflow_core\python\ops\resource_variable_ops.py", line 820, in assign
    self._shape.assert_is_compatible_with(value_tensor.shape)
  File "C:\Users\Alessandro\.conda\envs\keras\lib\site-packages\tensorflow_core\python\framework\tensor_shape.py", line 1111, in assert_is_compatible_with
    raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (3, 3, 3, 32) and (1, 1, 960, 320) are incompatible
import tensorflow as tf
from tensorflow_examples.models.pix2pix import pix2pix
import tensorflow_datasets as tfds

from tensorflow_model_optimization.python.core.quantization.keras.quantize import quantize_apply, quantize_annotate_layer


tfds.disable_progress_bar()

from IPython.display import clear_output
import matplotlib.pyplot as plt

dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)


def normalize(input_image, input_mask):
    input_image = tf.cast(input_image, tf.float32) / 255.0
    input_mask -= 1
    return input_image, input_mask


@tf.function
def load_image_train(datapoint):
    input_image = tf.image.resize(datapoint['image'], (128, 128))
    input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))

    if tf.random.uniform(()) > 0.5:
        input_image = tf.image.flip_left_right(input_image)
        input_mask = tf.image.flip_left_right(input_mask)

    input_image, input_mask = normalize(input_image, input_mask)

    return input_image, input_mask


def load_image_test(datapoint):
    input_image = tf.image.resize(datapoint['image'], (128, 128))
    input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))

    input_image, input_mask = normalize(input_image, input_mask)

    return input_image, input_mask


TRAIN_LENGTH = info.splits['train'].num_examples
BATCH_SIZE = 64
BUFFER_SIZE = 1000
STEPS_PER_EPOCH = TRAIN_LENGTH // BATCH_SIZE

train = dataset['train'].map(load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE)
test = dataset['test'].map(load_image_test)

train_dataset = train.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()
train_dataset = train_dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
test_dataset = test.batch(BATCH_SIZE)


def display(display_list):
    plt.figure(figsize=(15, 15))

    title = ['Input Image', 'True Mask', 'Predicted Mask']

    for i in range(len(display_list)):
        plt.subplot(1, len(display_list), i + 1)
        plt.title(title[i])
        plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i]))
        plt.axis('off')
    plt.show()
#

for image, mask in train.take(1):
    sample_image, sample_mask = image, mask

# display([sample_image, sample_mask])

OUTPUT_CHANNELS = 3

base_model = tf.keras.applications.MobileNetV2(input_shape=[128, 128, 3], include_top=False)


# Use the activations of these layers
layer_names = [
    'block_1_expand_relu',  # 64x64
    'block_3_expand_relu',  # 32x32
    'block_6_expand_relu',  # 16x16
    'block_13_expand_relu',  # 8x8
    'block_16_project',  # 4x4
]

print([layer.name for layer in base_model.layers])

layers = [base_model.get_layer(name).output for name in layer_names]

# Create the feature extraction model
down_stack = tf.keras.Model(inputs=base_model.input, outputs=layers)

down_stack.trainable = False

up_stack = [
    pix2pix.upsample(512, 3),  # 4x4 -> 8x8
    pix2pix.upsample(256, 3),  # 8x8 -> 16x16
    pix2pix.upsample(128, 3),  # 16x16 -> 32x32
    pix2pix.upsample(64, 3),  # 32x32 -> 64x64
]


def unet_model(output_channels):
    inputs = tf.keras.layers.Input(shape=[128, 128, 3])
    x = inputs

    # Downsampling through the model
    skips = down_stack(x)
    x = skips[-1]
    skips = reversed(skips[:-1])

    # Upsampling and establishing the skip connections
    for up, skip in zip(up_stack, skips):
        x = up(x)
        concat = tf.keras.layers.Concatenate()
        x = concat([x, skip])

    # This is the last layer of the model
    last = quantize_annotate_layer(tf.keras.layers.Conv2DTranspose(
        output_channels, 3, strides=2,
        padding='same',
        name="unet_transposed_conv"))  # 64x64 -> 128x128

    x = last(x)

    return quantize_apply(tf.keras.Model(inputs=inputs, outputs=x))


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

tf.keras.utils.plot_model(model, show_shapes=True)


def create_mask(pred_mask):
    pred_mask = tf.argmax(pred_mask, axis=-1)
    pred_mask = pred_mask[..., tf.newaxis]
    return pred_mask[0]


def show_predictions(dataset=None, num=1):
    if dataset:
        for image, mask in dataset.take(num):
            pred_mask = model.predict(image)
            display([image[0], mask[0], create_mask(pred_mask)])
    else:
        display([sample_image, sample_mask,
                 create_mask(model.predict(sample_image[tf.newaxis, ...]))])


show_predictions()


class DisplayCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        clear_output(wait=True)
        show_predictions()
        print('\nSample Prediction after epoch {}\n'.format(epoch + 1))


EPOCHS = 20
VAL_SUBSPLITS = 5
VALIDATION_STEPS = info.splits['test'].num_examples // BATCH_SIZE // VAL_SUBSPLITS

model_history = model.fit(train_dataset, epochs=EPOCHS,
                          steps_per_epoch=STEPS_PER_EPOCH,
                          validation_steps=VALIDATION_STEPS,
                          validation_data=test_dataset,
                          callbacks=[DisplayCallback()])

loss = model_history.history['loss']
val_loss = model_history.history['val_loss']

epochs = range(EPOCHS)

plt.figure()
plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'bo', label='Validation loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss Value')
plt.ylim([0, 1])
plt.legend()
plt.show()

show_predictions(test_dataset, 3)

alessandroaimar avatar Jun 09 '20 17:06 alessandroaimar

@nutsiepully Is there a suggested workaround for this?

ppershing avatar Aug 09 '20 12:08 ppershing

Hi @kalaluthien, sorry for the long delay. Is this still an issue for you?

Hi @nutsiepully, can you update?

teijeong avatar Apr 14 '21 09:04 teijeong

@Xhark recently submitted a fix for this. He should be able to point to it.

nutsiepully avatar Apr 14 '21 18:04 nutsiepully

Yeah This bug is fixed, it might run without error now.

But If you want to quantize custom layer, you have be careful to put Quantizer. Because QAT Transforms and TFLite converter are only accept very optimistic quantization patterns.

Now you can try your own quantizer, but I can't guarantee it works properly.

We are preparing an example for it. (Custom layer case) Please wait a bit!

Xhark avatar Apr 16 '21 06:04 Xhark

Thank you for your reminder. I'll share this patch to our company. BTW, I have workaround this issue by porting every internal custom layer to the bunch of functional layers.

kalaluthien avatar Apr 23 '21 07:04 kalaluthien