Path: blob/master/examples/vision/focal_modulation_network.py
3507 views
"""1Title: Focal Modulation: A replacement for Self-Attention2Author: [Aritra Roy Gosthipaty](https://twitter.com/ariG23498), [Ritwik Raha](https://twitter.com/ritwik_raha)3Date created: 2023/01/254Last modified: 2023/02/155Description: Image classification with Focal Modulation Networks.6Accelerator: GPU7"""89"""10## Introduction1112This tutorial aims to provide a comprehensive guide to the implementation of13Focal Modulation Networks, as presented in14[Yang et al.](https://arxiv.org/abs/2203.11926).1516This tutorial will provide a formal, minimalistic approach to implementing Focal17Modulation Networks and explore its potential applications in the field of Deep Learning.1819**Problem statement**2021The Transformer architecture ([Vaswani et al.](https://arxiv.org/abs/1706.03762)),22which has become the de facto standard in most Natural Language Processing tasks, has23also been applied to the field of computer vision, e.g. Vision24Transformers ([Dosovitskiy et al.](https://arxiv.org/abs/2010.11929v2)).2526> In Transformers, the self-attention (SA) is arguably the key to its success which27enables input-dependent global interactions, in contrast to convolution operation which28constraints interactions in a local region with a shared kernel.2930The **Attention** module is mathematically written as shown in **Equation 1**.3132|  |33| :--: |34| Equation 1: The mathematical equation of attention (Source: Aritra and Ritwik) |3536Where:3738- `Q` is the query39- `K` is the key40- `V` is the value41- `d_k` is the dimension of the key4243With **self-attention**, the query, key, and value are all sourced from the input44sequence. Let us rewrite the attention equation for self-attention as shown in **Equation452**.4647|  |48| :--: |49| Equation 2: The mathematical equation of self-attention (Source: Aritra and Ritwik) |5051Upon looking at the equation of self-attention, we see that it is a quadratic equation.52Therefore, as the number of tokens increase, so does the computation time (cost too). To53mitigate this problem and make Transformers more interpretable, Yang et al.54have tried to replace the Self-Attention module with better components.5556**The Solution**5758Yang et al. introduce the Focal Modulation layer to serve as a59seamless replacement for the Self-Attention Layer. The layer boasts high60interpretability, making it a valuable tool for Deep Learning practitioners.6162In this tutorial, we will delve into the practical application of this layer by training63the entire model on the CIFAR-10 dataset and visually interpreting the layer's64performance.6566Note: We try to align our implementation with the67[official implementation](https://github.com/microsoft/FocalNet).68"""6970"""71## Setup and Imports7273We use tensorflow version `2.11.0` for this tutorial.74"""7576import numpy as np77import tensorflow as tf78from tensorflow import keras79from tensorflow.keras import layers80from tensorflow.keras.optimizers.experimental import AdamW81from typing import Optional, Tuple, List82from matplotlib import pyplot as plt83from random import randint8485# Set seed for reproducibility.86tf.keras.utils.set_random_seed(42)8788"""89## Global Configuration9091We do not have any strong rationale behind choosing these hyperparameters. Please feel92free to change the configuration and train the model.93"""9495# DATA96TRAIN_SLICE = 4000097BUFFER_SIZE = 204898BATCH_SIZE = 102499AUTO = tf.data.AUTOTUNE100INPUT_SHAPE = (32, 32, 3)101IMAGE_SIZE = 48102NUM_CLASSES = 10103104# OPTIMIZER105LEARNING_RATE = 1e-4106WEIGHT_DECAY = 1e-4107108# TRAINING109EPOCHS = 25110111"""112## Load and process the CIFAR-10 dataset113"""114115(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()116(x_train, y_train), (x_val, y_val) = (117(x_train[:TRAIN_SLICE], y_train[:TRAIN_SLICE]),118(x_train[TRAIN_SLICE:], y_train[TRAIN_SLICE:]),119)120121"""122### Build the augmentations123124We use the `keras.Sequential` API to compose all the individual augmentation steps125into one API.126"""127128# Build the `train` augmentation pipeline.129train_aug = keras.Sequential(130[131layers.Rescaling(1 / 255.0),132layers.Resizing(INPUT_SHAPE[0] + 20, INPUT_SHAPE[0] + 20),133layers.RandomCrop(IMAGE_SIZE, IMAGE_SIZE),134layers.RandomFlip("horizontal"),135],136name="train_data_augmentation",137)138139# Build the `val` and `test` data pipeline.140test_aug = keras.Sequential(141[142layers.Rescaling(1 / 255.0),143layers.Resizing(IMAGE_SIZE, IMAGE_SIZE),144],145name="test_data_augmentation",146)147148"""149### Build `tf.data` pipeline150"""151152train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))153train_ds = (154train_ds.map(155lambda image, label: (train_aug(image), label), num_parallel_calls=AUTO156)157.shuffle(BUFFER_SIZE)158.batch(BATCH_SIZE)159.prefetch(AUTO)160)161162val_ds = tf.data.Dataset.from_tensor_slices((x_val, y_val))163val_ds = (164val_ds.map(lambda image, label: (test_aug(image), label), num_parallel_calls=AUTO)165.batch(BATCH_SIZE)166.prefetch(AUTO)167)168169test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test))170test_ds = (171test_ds.map(lambda image, label: (test_aug(image), label), num_parallel_calls=AUTO)172.batch(BATCH_SIZE)173.prefetch(AUTO)174)175176"""177## Architecture178179We pause here to take a quick look at the Architecture of the Focal Modulation Network.180**Figure 1** shows how every individual layer is compiled into a single model. This gives181us a bird's eye view of the entire architecture.182183|  |184| :--: |185| Figure 1: A diagram of the Focal Modulation model (Source: Aritra and Ritwik) |186187We dive deep into each of these layers in the following sections. This is the order we188will follow:189190191- Patch Embedding Layer192- Focal Modulation Block193- Multi-Layer Perceptron194- Focal Modulation Layer195- Hierarchical Contextualization196- Gated Aggregation197- Building Focal Modulation Block198- Building the Basic Layer199200To better understand the architecture in a format we are well versed in, let us see how201the Focal Modulation Network would look when drawn like a Transformer architecture.202203**Figure 2** shows the encoder layer of a traditional Transformer architecture where Self204Attention is replaced with the Focal Modulation layer.205206The <font color="blue">blue</font> blocks represent the Focal Modulation block. A stack207of these blocks builds a single Basic Layer. The <font color="green">green</font> blocks208represent the Focal Modulation layer.209210|  |211| :--: |212| Figure 2: The Entire Architecture (Source: Aritra and Ritwik) |213"""214215"""216## Patch Embedding Layer217218The patch embedding layer is used to patchify the input images and project them into a219latent space. This layer is also used as the down-sampling layer in the architecture.220"""221222223class PatchEmbed(layers.Layer):224"""Image patch embedding layer, also acts as the down-sampling layer.225226Args:227image_size (Tuple[int]): Input image resolution.228patch_size (Tuple[int]): Patch spatial resolution.229embed_dim (int): Embedding dimension.230"""231232def __init__(233self,234image_size: Tuple[int] = (224, 224),235patch_size: Tuple[int] = (4, 4),236embed_dim: int = 96,237**kwargs,238):239super().__init__(**kwargs)240patch_resolution = [241image_size[0] // patch_size[0],242image_size[1] // patch_size[1],243]244self.image_size = image_size245self.patch_size = patch_size246self.embed_dim = embed_dim247self.patch_resolution = patch_resolution248self.num_patches = patch_resolution[0] * patch_resolution[1]249self.proj = layers.Conv2D(250filters=embed_dim, kernel_size=patch_size, strides=patch_size251)252self.flatten = layers.Reshape(target_shape=(-1, embed_dim))253self.norm = keras.layers.LayerNormalization(epsilon=1e-7)254255def call(self, x: tf.Tensor) -> Tuple[tf.Tensor, int, int, int]:256"""Patchifies the image and converts into tokens.257258Args:259x: Tensor of shape (B, H, W, C)260261Returns:262A tuple of the processed tensor, height of the projected263feature map, width of the projected feature map, number264of channels of the projected feature map.265"""266# Project the inputs.267x = self.proj(x)268269# Obtain the shape from the projected tensor.270height = tf.shape(x)[1]271width = tf.shape(x)[2]272channels = tf.shape(x)[3]273274# B, H, W, C -> B, H*W, C275x = self.norm(self.flatten(x))276277return x, height, width, channels278279280"""281## Focal Modulation block282283A Focal Modulation block can be considered as a single Transformer Block with the Self284Attention (SA) module being replaced with Focal Modulation module, as we saw in **Figure2852**.286287Let us recall how a focal modulation block is supposed to look like with the aid of the288**Figure 3**.289290291|  |292| :--: |293| Figure 3: The isolated view of the Focal Modulation Block (Source: Aritra and Ritwik) |294295The Focal Modulation Block consists of:296- Multilayer Perceptron297- Focal Modulation layer298"""299300"""301### Multilayer Perceptron302"""303304305def MLP(306in_features: int,307hidden_features: Optional[int] = None,308out_features: Optional[int] = None,309mlp_drop_rate: float = 0.0,310):311hidden_features = hidden_features or in_features312out_features = out_features or in_features313314return keras.Sequential(315[316layers.Dense(units=hidden_features, activation=keras.activations.gelu),317layers.Dense(units=out_features),318layers.Dropout(rate=mlp_drop_rate),319]320)321322323"""324### Focal Modulation layer325326In a typical Transformer architecture, for each visual token (**query**) `x_i in R^C` in327an input feature map `X in R^{HxWxC}` a **generic encoding process** produces a feature328representation `y_i in R^C`.329330The encoding process consists of **interaction** (with its surroundings for e.g. a dot331product), and **aggregation** (over the contexts for e.g weighted mean).332333We will talk about two types of encoding here:334- Interaction and then Aggregation in **Self-Attention**335- Aggregation and then Interaction in **Focal Modulation**336337**Self-Attention**338339|  |340| :--: |341| **Figure 4**: Self-Attention module. (Source: Aritra and Ritwik) |342343|  |344| :--: |345| **Equation 3:** Aggregation and Interaction in Self-Attention(Surce: Aritra and Ritwik)|346347As shown in **Figure 4** the query and the key interact (in the interaction step) with348each other to output the attention scores. The weighted aggregation of the value comes349next, known as the aggregation step.350351**Focal Modulation**352353|  |354| :--: |355| **Figure 5**: Focal Modulation module. (Source: Aritra and Ritwik) |356357|  |358| :--: |359| **Equation 4:** Aggregation and Interaction in Focal Modulation (Source: Aritra and Ritwik) |360361**Figure 5** depicts the Focal Modulation layer. `q()` is the query projection362function. It is a **linear layer** that projects the query into a latent space. `m ()` is363the context aggregation function. Unlike self-attention, the364aggregation step takes place in focal modulation before the interaction step.365"""366367"""368While `q()` is pretty straightforward to understand, the context aggregation function369`m()` is more complex. Therefore, this section will focus on `m()`.370371| |372| :--: |373| **Figure 6**: Context Aggregation function `m()`. (Source: Aritra and Ritwik) |374375The context aggregation function `m()` consists of two parts as shown in **Figure 6**:376- Hierarchical Contextualization377- Gated Aggregation378"""379380"""381#### Hierarchical Contextualization382383| |384| :--: |385| **Figure 7**: Hierarchical Contextualization (Source: Aritra and Ritwik) |386387In **Figure 7**, we see that the input is first projected linearly. This linear projection388produces `Z^0`. Where `Z^0` can be expressed as follows:389390|  |391| :--: |392| Equation 5: Linear projection of `Z^0` (Source: Aritra and Ritwik) |393394`Z^0` is then passed on to a series of Depth-Wise (DWConv) Conv and395[GeLU](https://www.tensorflow.org/api_docs/python/tf/keras/activations/gelu) layers. The396authors term each block of DWConv and GeLU as levels denoted by `l`. In **Figure 6** we397have two levels. Mathematically this is represented as:398399|  |400| :--: |401| Equation 6: Levels of the modulation layer (Source: Aritra and Ritwik) |402403where `l in {1, ... , L}`404405The final feature map goes through a Global Average Pooling Layer. This can be expressed406as follows:407408|  |409| :--: |410| Equation 7: Average Pooling of the final feature (Source: Aritra and Ritwik)|411"""412413"""414#### Gated Aggregation415416| |417| :--: |418| **Figure 8**: Gated Aggregation (Source: Aritra and Ritwik) |419420Now that we have `L+1` intermediate feature maps by virtue of the Hierarchical421Contextualization step, we need a gating mechanism that lets some features pass and422prohibits others. This can be implemented with the attention module.423Later in the tutorial, we will visualize these gates to better understand their424usefulness.425426First, we build the weights for aggregation. Here we apply a **linear layer** on the input427feature map that projects it into `L+1` dimensions.428429|  |430| :--: |431| Eqation 8: Gates (Source: Aritra and Ritwik) |432433Next we perform the weighted aggregation over the contexts.434435|  |436| :--: |437| Eqation 9: Final feature map (Source: Aritra and Ritwik) |438439To enable communication across different channels, we use another linear layer `h()`440to obtain the modulator441442|  |443| :--: |444| Eqation 10: Modulator (Source: Aritra and Ritwik) |445446To sum up the Focal Modulation layer we have:447448|  |449| :--: |450| Eqation 11: Focal Modulation Layer (Source: Aritra and Ritwik) |451"""452453454class FocalModulationLayer(layers.Layer):455"""The Focal Modulation layer includes query projection & context aggregation.456457Args:458dim (int): Projection dimension.459focal_window (int): Window size for focal modulation.460focal_level (int): The current focal level.461focal_factor (int): Factor of focal modulation.462proj_drop_rate (float): Rate of dropout.463"""464465def __init__(466self,467dim: int,468focal_window: int,469focal_level: int,470focal_factor: int = 2,471proj_drop_rate: float = 0.0,472**kwargs,473):474super().__init__(**kwargs)475self.dim = dim476self.focal_window = focal_window477self.focal_level = focal_level478self.focal_factor = focal_factor479self.proj_drop_rate = proj_drop_rate480481# Project the input feature into a new feature space using a482# linear layer. Note the `units` used. We will be projecting the input483# feature all at once and split the projection into query, context,484# and gates.485self.initial_proj = layers.Dense(486units=(2 * self.dim) + (self.focal_level + 1),487use_bias=True,488)489self.focal_layers = list()490self.kernel_sizes = list()491for idx in range(self.focal_level):492kernel_size = (self.focal_factor * idx) + self.focal_window493depth_gelu_block = keras.Sequential(494[495layers.ZeroPadding2D(padding=(kernel_size // 2, kernel_size // 2)),496layers.Conv2D(497filters=self.dim,498kernel_size=kernel_size,499activation=keras.activations.gelu,500groups=self.dim,501use_bias=False,502),503]504)505self.focal_layers.append(depth_gelu_block)506self.kernel_sizes.append(kernel_size)507self.activation = keras.activations.gelu508self.gap = layers.GlobalAveragePooling2D(keepdims=True)509self.modulator_proj = layers.Conv2D(510filters=self.dim,511kernel_size=(1, 1),512use_bias=True,513)514self.proj = layers.Dense(units=self.dim)515self.proj_drop = layers.Dropout(self.proj_drop_rate)516517def call(self, x: tf.Tensor, training: Optional[bool] = None) -> tf.Tensor:518"""Forward pass of the layer.519520Args:521x: Tensor of shape (B, H, W, C)522"""523# Apply the linear projecion to the input feature map524x_proj = self.initial_proj(x)525526# Split the projected x into query, context and gates527query, context, self.gates = tf.split(528value=x_proj,529num_or_size_splits=[self.dim, self.dim, self.focal_level + 1],530axis=-1,531)532533# Context aggregation534context = self.focal_layers[0](context)535context_all = context * self.gates[..., 0:1]536for idx in range(1, self.focal_level):537context = self.focal_layers[idx](context)538context_all += context * self.gates[..., idx : idx + 1]539540# Build the global context541context_global = self.activation(self.gap(context))542context_all += context_global * self.gates[..., self.focal_level :]543544# Focal Modulation545self.modulator = self.modulator_proj(context_all)546x_output = query * self.modulator547548# Project the output and apply dropout549x_output = self.proj(x_output)550x_output = self.proj_drop(x_output)551552return x_output553554555"""556### The Focal Modulation block557558Finally, we have all the components we need to build the Focal Modulation block. Here we559take the MLP and Focal Modulation layer together and build the Focal Modulation block.560"""561562563class FocalModulationBlock(layers.Layer):564"""Combine FFN and Focal Modulation Layer.565566Args:567dim (int): Number of input channels.568input_resolution (Tuple[int]): Input resulotion.569mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.570drop (float): Dropout rate.571drop_path (float): Stochastic depth rate.572focal_level (int): Number of focal levels.573focal_window (int): Focal window size at first focal level574"""575576def __init__(577self,578dim: int,579input_resolution: Tuple[int],580mlp_ratio: float = 4.0,581drop: float = 0.0,582drop_path: float = 0.0,583focal_level: int = 1,584focal_window: int = 3,585**kwargs,586):587super().__init__(**kwargs)588self.dim = dim589self.input_resolution = input_resolution590self.mlp_ratio = mlp_ratio591self.focal_level = focal_level592self.focal_window = focal_window593self.norm = layers.LayerNormalization(epsilon=1e-5)594self.modulation = FocalModulationLayer(595dim=self.dim,596focal_window=self.focal_window,597focal_level=self.focal_level,598proj_drop_rate=drop,599)600mlp_hidden_dim = int(self.dim * self.mlp_ratio)601self.mlp = MLP(602in_features=self.dim,603hidden_features=mlp_hidden_dim,604mlp_drop_rate=drop,605)606607def call(self, x: tf.Tensor, height: int, width: int, channels: int) -> tf.Tensor:608"""Processes the input tensor through the focal modulation block.609610Args:611x (tf.Tensor): Inputs of the shape (B, L, C)612height (int): The height of the feature map613width (int): The width of the feature map614channels (int): The number of channels of the feature map615616Returns:617The processed tensor.618"""619shortcut = x620621# Focal Modulation622x = tf.reshape(x, shape=(-1, height, width, channels))623x = self.modulation(x)624x = tf.reshape(x, shape=(-1, height * width, channels))625626# FFN627x = shortcut + x628x = x + self.mlp(self.norm(x))629return x630631632"""633## The Basic Layer634635The basic layer consists of a collection of Focal Modulation blocks. This is636illustrated in **Figure 9**.637638|  |639| :--: |640| **Figure 9**: Basic Layer, a collection of focal modulation blocks. (Source: Aritra and Ritwik) |641642Notice how in **Fig. 9** there are more than one focal modulation blocks denoted by `Nx`.643This shows how the Basic Layer is a collection of Focal Modulation blocks.644"""645646647class BasicLayer(layers.Layer):648"""Collection of Focal Modulation Blocks.649650Args:651dim (int): Dimensions of the model.652out_dim (int): Dimension used by the Patch Embedding Layer.653input_resolution (Tuple[int]): Input image resolution.654depth (int): The number of Focal Modulation Blocks.655mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.656drop (float): Dropout rate.657downsample (tf.keras.layers.Layer): Downsampling layer at the end of the layer.658focal_level (int): The current focal level.659focal_window (int): Focal window used.660"""661662def __init__(663self,664dim: int,665out_dim: int,666input_resolution: Tuple[int],667depth: int,668mlp_ratio: float = 4.0,669drop: float = 0.0,670downsample=None,671focal_level: int = 1,672focal_window: int = 1,673**kwargs,674):675super().__init__(**kwargs)676self.dim = dim677self.input_resolution = input_resolution678self.depth = depth679self.blocks = [680FocalModulationBlock(681dim=dim,682input_resolution=input_resolution,683mlp_ratio=mlp_ratio,684drop=drop,685focal_level=focal_level,686focal_window=focal_window,687)688for i in range(self.depth)689]690691# Downsample layer at the end of the layer692if downsample is not None:693self.downsample = downsample(694image_size=input_resolution,695patch_size=(2, 2),696embed_dim=out_dim,697)698else:699self.downsample = None700701def call(702self, x: tf.Tensor, height: int, width: int, channels: int703) -> Tuple[tf.Tensor, int, int, int]:704"""Forward pass of the layer.705706Args:707x (tf.Tensor): Tensor of shape (B, L, C)708height (int): Height of feature map709width (int): Width of feature map710channels (int): Embed Dim of feature map711712Returns:713A tuple of the processed tensor, changed height, width, and714dim of the tensor.715"""716# Apply Focal Modulation Blocks717for block in self.blocks:718x = block(x, height, width, channels)719720# Except the last Basic Layer, all the layers have721# downsample at the end of it.722if self.downsample is not None:723x = tf.reshape(x, shape=(-1, height, width, channels))724x, height_o, width_o, channels_o = self.downsample(x)725else:726height_o, width_o, channels_o = height, width, channels727728return x, height_o, width_o, channels_o729730731"""732## The Focal Modulation Network model733734This is the model that ties everything together.735It consists of a collection of Basic Layers with a classification head.736For a recap of how this is structured refer to **Figure 1**.737"""738739740class FocalModulationNetwork(keras.Model):741"""The Focal Modulation Network.742743Parameters:744image_size (Tuple[int]): Spatial size of images used.745patch_size (Tuple[int]): Patch size of each patch.746num_classes (int): Number of classes used for classification.747embed_dim (int): Patch embedding dimension.748depths (List[int]): Depth of each Focal Transformer block.749mlp_ratio (float): Ratio of expansion for the intermediate layer of MLP.750drop_rate (float): The dropout rate for FM and MLP layers.751focal_levels (list): How many focal levels at all stages.752Note that this excludes the finest-grain level.753focal_windows (list): The focal window size at all stages.754"""755756def __init__(757self,758image_size: Tuple[int] = (48, 48),759patch_size: Tuple[int] = (4, 4),760num_classes: int = 10,761embed_dim: int = 256,762depths: List[int] = [2, 3, 2],763mlp_ratio: float = 4.0,764drop_rate: float = 0.1,765focal_levels=[2, 2, 2],766focal_windows=[3, 3, 3],767**kwargs,768):769super().__init__(**kwargs)770self.num_layers = len(depths)771embed_dim = [embed_dim * (2**i) for i in range(self.num_layers)]772self.num_classes = num_classes773self.embed_dim = embed_dim774self.num_features = embed_dim[-1]775self.mlp_ratio = mlp_ratio776self.patch_embed = PatchEmbed(777image_size=image_size,778patch_size=patch_size,779embed_dim=embed_dim[0],780)781num_patches = self.patch_embed.num_patches782patches_resolution = self.patch_embed.patch_resolution783self.patches_resolution = patches_resolution784self.pos_drop = layers.Dropout(drop_rate)785self.basic_layers = list()786for i_layer in range(self.num_layers):787layer = BasicLayer(788dim=embed_dim[i_layer],789out_dim=(790embed_dim[i_layer + 1] if (i_layer < self.num_layers - 1) else None791),792input_resolution=(793patches_resolution[0] // (2**i_layer),794patches_resolution[1] // (2**i_layer),795),796depth=depths[i_layer],797mlp_ratio=self.mlp_ratio,798drop=drop_rate,799downsample=PatchEmbed if (i_layer < self.num_layers - 1) else None,800focal_level=focal_levels[i_layer],801focal_window=focal_windows[i_layer],802)803self.basic_layers.append(layer)804self.norm = keras.layers.LayerNormalization(epsilon=1e-7)805self.avgpool = layers.GlobalAveragePooling1D()806self.flatten = layers.Flatten()807self.head = layers.Dense(self.num_classes, activation="softmax")808809def call(self, x: tf.Tensor) -> tf.Tensor:810"""Forward pass of the layer.811812Args:813x: Tensor of shape (B, H, W, C)814815Returns:816The logits.817"""818# Patch Embed the input images.819x, height, width, channels = self.patch_embed(x)820x = self.pos_drop(x)821822for idx, layer in enumerate(self.basic_layers):823x, height, width, channels = layer(x, height, width, channels)824825x = self.norm(x)826x = self.avgpool(x)827x = self.flatten(x)828x = self.head(x)829return x830831832"""833## Train the model834835Now with all the components in place and the architecture actually built, we are ready to836put it to good use.837838In this section, we train our Focal Modulation model on the CIFAR-10 dataset.839"""840841"""842### Visualization Callback843844A key feature of the Focal Modulation Network is explicit input-dependency. This means845the modulator is calculated by looking at the local features around the target location,846so it depends on the input. In very simple terms, this makes interpretation easy. We can847simply lay down the gating values and the original image, next to each other to see how848the gating mechanism works.849850The authors of the paper visualize the gates and the modulator in order to focus on the851interpretability of the Focal Modulation layer. Below is a visualization852callback that shows the gates and modulator of a specific layer in the model while the853model trains.854855We will notice later that as the model trains, the visualizations get better.856857The gates appear to selectively permit certain aspects of the input image to pass858through, while gently disregarding others, ultimately leading to improved classification859accuracy.860"""861862863def display_grid(864test_images: tf.Tensor,865gates: tf.Tensor,866modulator: tf.Tensor,867):868"""Displays the image with the gates and modulator overlayed.869870Args:871test_images (tf.Tensor): A batch of test images.872gates (tf.Tensor): The gates of the Focal Modualtion Layer.873modulator (tf.Tensor): The modulator of the Focal Modulation Layer.874"""875fig, ax = plt.subplots(nrows=1, ncols=5, figsize=(25, 5))876877# Radomly sample an image from the batch.878index = randint(0, BATCH_SIZE - 1)879orig_image = test_images[index]880gate_image = gates[index]881modulator_image = modulator[index]882883# Original Image884ax[0].imshow(orig_image)885ax[0].set_title("Original:")886ax[0].axis("off")887888for index in range(1, 5):889img = ax[index].imshow(orig_image)890if index != 4:891overlay_image = gate_image[..., index - 1]892title = f"G {index}:"893else:894overlay_image = tf.norm(modulator_image, ord=2, axis=-1)895title = f"MOD:"896897ax[index].imshow(898overlay_image, cmap="inferno", alpha=0.6, extent=img.get_extent()899)900ax[index].set_title(title)901ax[index].axis("off")902903plt.axis("off")904plt.show()905plt.close()906907908"""909### TrainMonitor910"""911912# Taking a batch of test inputs to measure the model's progress.913test_images, test_labels = next(iter(test_ds))914upsampler = tf.keras.layers.UpSampling2D(915size=(4, 4),916interpolation="bilinear",917)918919920class TrainMonitor(keras.callbacks.Callback):921def __init__(self, epoch_interval=None):922self.epoch_interval = epoch_interval923924def on_epoch_end(self, epoch, logs=None):925if self.epoch_interval and epoch % self.epoch_interval == 0:926_ = self.model(test_images)927928# Take the mid layer for visualization929gates = self.model.basic_layers[1].blocks[-1].modulation.gates930gates = upsampler(gates)931modulator = self.model.basic_layers[1].blocks[-1].modulation.modulator932modulator = upsampler(modulator)933934# Display the grid of gates and modulator.935display_grid(test_images=test_images, gates=gates, modulator=modulator)936937938"""939### Learning Rate scheduler940"""941942943# Some code is taken from:944# https://www.kaggle.com/ashusma/training-rfcx-tensorflow-tpu-effnet-b2.945class WarmUpCosine(keras.optimizers.schedules.LearningRateSchedule):946def __init__(947self, learning_rate_base, total_steps, warmup_learning_rate, warmup_steps948):949super().__init__()950self.learning_rate_base = learning_rate_base951self.total_steps = total_steps952self.warmup_learning_rate = warmup_learning_rate953self.warmup_steps = warmup_steps954self.pi = tf.constant(np.pi)955956def __call__(self, step):957if self.total_steps < self.warmup_steps:958raise ValueError("Total_steps must be larger or equal to warmup_steps.")959cos_annealed_lr = tf.cos(960self.pi961* (tf.cast(step, tf.float32) - self.warmup_steps)962/ float(self.total_steps - self.warmup_steps)963)964learning_rate = 0.5 * self.learning_rate_base * (1 + cos_annealed_lr)965if self.warmup_steps > 0:966if self.learning_rate_base < self.warmup_learning_rate:967raise ValueError(968"Learning_rate_base must be larger or equal to "969"warmup_learning_rate."970)971slope = (972self.learning_rate_base - self.warmup_learning_rate973) / self.warmup_steps974warmup_rate = slope * tf.cast(step, tf.float32) + self.warmup_learning_rate975learning_rate = tf.where(976step < self.warmup_steps, warmup_rate, learning_rate977)978return tf.where(979step > self.total_steps, 0.0, learning_rate, name="learning_rate"980)981982983total_steps = int((len(x_train) / BATCH_SIZE) * EPOCHS)984warmup_epoch_percentage = 0.15985warmup_steps = int(total_steps * warmup_epoch_percentage)986scheduled_lrs = WarmUpCosine(987learning_rate_base=LEARNING_RATE,988total_steps=total_steps,989warmup_learning_rate=0.0,990warmup_steps=warmup_steps,991)992993"""994### Initialize, compile and train the model995"""996997focal_mod_net = FocalModulationNetwork()998optimizer = AdamW(learning_rate=scheduled_lrs, weight_decay=WEIGHT_DECAY)9991000# Compile and train the model.1001focal_mod_net.compile(1002optimizer=optimizer,1003loss="sparse_categorical_crossentropy",1004metrics=["accuracy"],1005)1006history = focal_mod_net.fit(1007train_ds,1008epochs=EPOCHS,1009validation_data=val_ds,1010callbacks=[TrainMonitor(epoch_interval=10)],1011)10121013"""1014## Plot loss and accuracy1015"""10161017plt.plot(history.history["loss"], label="loss")1018plt.plot(history.history["val_loss"], label="val_loss")1019plt.legend()1020plt.show()10211022plt.plot(history.history["accuracy"], label="accuracy")1023plt.plot(history.history["val_accuracy"], label="val_accuracy")1024plt.legend()1025plt.show()10261027"""1028## Test visualizations10291030Let's test our model on some test images and see how the gates look like.1031"""10321033test_images, test_labels = next(iter(test_ds))1034_ = focal_mod_net(test_images)10351036# Take the mid layer for visualization1037gates = focal_mod_net.basic_layers[1].blocks[-1].modulation.gates1038gates = upsampler(gates)1039modulator = focal_mod_net.basic_layers[1].blocks[-1].modulation.modulator1040modulator = upsampler(modulator)10411042# Plot the test images with the gates and modulator overlayed.1043for row in range(5):1044display_grid(1045test_images=test_images,1046gates=gates,1047modulator=modulator,1048)10491050"""1051## Conclusion10521053The proposed architecture, the Focal Modulation Network1054architecture is a mechanism that allows different1055parts of an image to interact with each other in a way that depends on the image itself.1056It works by first gathering different levels of context information around each part of1057the image (the "query token"), then using a gate to decide which context information is1058most relevant, and finally combining the chosen information in a simple but effective1059way.10601061This is meant as a replacement of Self-Attention mechanism from the Transformer1062architecture. The key feature that makes this research notable is not the conception of1063attention-less networks, but rather the introduction of a equally powerful architecture1064that is interpretable.10651066The authors also mention that they created a series of Focal Modulation Networks1067(FocalNets) that significantly outperform Self-Attention counterparts and with a fraction1068of parameters and pretraining data.10691070The FocalNets architecture has the potential to deliver impressive results and offers a1071simple implementation. Its promising performance and ease of use make it an attractive1072alternative to Self-Attention for researchers to explore in their own projects. It could1073potentially become widely adopted by the Deep Learning community in the near future.10741075## Acknowledgement10761077We would like to thank [PyImageSearch](https://pyimagesearch.com/) for providing with a1078Colab Pro account, [JarvisLabs.ai](https://cloud.jarvislabs.ai/) for GPU credits,1079and also Microsoft Research for providing an1080[official implementation](https://github.com/microsoft/FocalNet) of their paper.1081We would also like to extend our gratitude to the first author of the1082paper [Jianwei Yang](https://twitter.com/jw2yang4ai) who reviewed this tutorial1083extensively.1084"""108510861087