|
| 1 | +# Copyright 2023 The KerasCV Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import tensorflow as tf |
| 15 | + |
| 16 | +from keras_cv.layers.preprocessing.base_image_augmentation_layer import ( |
| 17 | + BaseImageAugmentationLayer, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +@tf.keras.utils.register_keras_serializable(package="keras_cv") |
| 22 | +class RepeatedAugmentation(BaseImageAugmentationLayer): |
| 23 | + """RepeatedAugmentation augments each image in a batch multiple times. |
| 24 | +
|
| 25 | + This technique exists to emulate the behavior of stochastic gradient descent within |
| 26 | + the context of mini-batch gradient descent. When training large vision models, |
| 27 | + choosing a large batch size can introduce too much noise into aggregated gradients |
| 28 | + causing the overall batch's gradients to be less effective than gradients produced |
| 29 | + using smaller gradients. RepeatedAugmentation handles this by re-using the same |
| 30 | + image multiple times within a batch creating correlated samples. |
| 31 | +
|
| 32 | + This layer increases your batch size by a factor of `len(augmenters)`. |
| 33 | +
|
| 34 | + Args: |
| 35 | + augmenters: the augmenters to use to augment the image |
| 36 | + shuffle: whether or not to shuffle the result. Essential when using an |
| 37 | + asynchronous distribution strategy such as ParameterServerStrategy. |
| 38 | +
|
| 39 | + Usage: |
| 40 | +
|
| 41 | + List of identical augmenters: |
| 42 | + ```python |
| 43 | + repeated_augment = cv_layers.RepeatedAugmentation( |
| 44 | + augmenters=[cv_layers.RandAugment(value_range=(0, 255))] * 8 |
| 45 | + ) |
| 46 | + inputs = { |
| 47 | + "images": tf.ones((8, 512, 512, 3)), |
| 48 | + "labels": tf.ones((8,)), |
| 49 | + } |
| 50 | + outputs = repeated_augment(inputs) |
| 51 | + # outputs now has a batch size of 64 because there are 8 augmenters |
| 52 | + ``` |
| 53 | +
|
| 54 | + List of distinct augmenters: |
| 55 | + ```python |
| 56 | + repeated_augment = cv_layers.RepeatedAugmentation( |
| 57 | + augmenters=[ |
| 58 | + cv_layers.RandAugment(value_range=(0, 255)), |
| 59 | + cv_layers.RandomFlip(), |
| 60 | + ] |
| 61 | + ) |
| 62 | + inputs = { |
| 63 | + "images": tf.ones((8, 512, 512, 3)), |
| 64 | + "labels": tf.ones((8,)), |
| 65 | + } |
| 66 | + outputs = repeated_augment(inputs) |
| 67 | + ``` |
| 68 | +
|
| 69 | + References: |
| 70 | + - [DEIT implementaton](https://github.com/facebookresearch/deit/blob/ee8893c8063f6937fec7096e47ba324c206e22b9/samplers.py#L8) |
| 71 | + - [Original publication](https://openaccess.thecvf.com/content_CVPR_2020/papers/Hoffer_Augment_Your_Batch_Improving_Generalization_Through_Instance_Repetition_CVPR_2020_paper.pdf) |
| 72 | +
|
| 73 | + """ |
| 74 | + |
| 75 | + def __init__(self, augmenters, shuffle=True, **kwargs): |
| 76 | + super().__init__(**kwargs) |
| 77 | + self.augmenters = augmenters |
| 78 | + self.shuffle = shuffle |
| 79 | + |
| 80 | + def _batch_augment(self, inputs): |
| 81 | + if "bounding_boxes" in inputs: |
| 82 | + raise ValueError( |
| 83 | + "RepeatedAugmentation() does not yet support bounding box labels." |
| 84 | + ) |
| 85 | + |
| 86 | + augmenter_outputs = [augmenter(inputs) for augmenter in self.augmenters] |
| 87 | + |
| 88 | + outputs = {} |
| 89 | + for k in inputs.keys(): |
| 90 | + outputs[k] = tf.concat([output[k] for output in augmenter_outputs], axis=0) |
| 91 | + |
| 92 | + if not self.shuffle: |
| 93 | + return outputs |
| 94 | + return self.shuffle_outputs(outputs) |
| 95 | + |
| 96 | + def shuffle_outputs(self, result): |
| 97 | + indices = tf.range(start=0, limit=tf.shape(result["images"])[0], dtype=tf.int32) |
| 98 | + indices = tf.random.shuffle(indices) |
| 99 | + for key in result: |
| 100 | + result[key] = tf.gather(result[key], indices) |
| 101 | + return result |
| 102 | + |
| 103 | + def _augment(self, inputs): |
| 104 | + raise ValueError( |
| 105 | + "RepeatedAugmentation() only works in batched mode. If " |
| 106 | + "you would like to create batches from a single image, use " |
| 107 | + "`x = tf.expand_dims(x, axis=0)` on your input images and labels." |
| 108 | + ) |
| 109 | + |
| 110 | + def get_config(self): |
| 111 | + config = super().get_config() |
| 112 | + config.update({"augmenters": self.augmenters, "shuffle": self.shuffle}) |
| 113 | + return config |
0 commit comments