Sitemap

Lion Optimizer

35 min readNov 30, 2023

--

Table of Contents (doubles as demo)

– Abstract
– Introduction
– AdamW Optimizer
– Lion Optimizer : What & Why
– Methodology
– Experimentation
– Conclusion
– References
– Appendix

Abstract

This blog delves into the world of Optimizers focussing mainly on the LION Optimizer and discussing what this optimizer brings new to the table. We compare this to the other commonly used optimizers like SGD, Momentum optimizer, NAG optimizer, RMSProp, Adagrad, Adam, AdamW while the main focus on AdamW since it is consider to be one of the best optimizers till date. For comparing these, we run many experiments like ablations on the hyperparameters, batch size ablation. We also try to visualize the loss landscapes of Lion and AdamW. We do all of this on various kinds of ML tasks such as Image classification, sentiment analysis, etc. For better understanding, we also try to do these tasks on different models and datasets. The main motive here is to understand Lion optimizer and try to see if it is better than the other optimizers. Appendix contains detailed explanations of the few things which we skimmed through in the main blog.

Introduction

What is a Neural Network?

Neural networks are computer models inspired by the human brain, consisting of layers of interconnected nodes (neurons) that perform simple computations. These networks learn by adjusting the strengths of connections between nodes.
A basic example is a linear regression model, where the network learns parameters (like a1 and a2) to approximate an output Y from an input X. The network’s accuracy is improved by minimizing a loss function, such as the Mean Squared Error (MSE), which measures the difference between predicted and actual values. To optimize these parameters, the network calculates gradients, which are vectors of partial derivatives showing how the loss changes with each parameter. The parameters are then updated in the direction opposite to the gradient, guided by a learning rate, effectively reducing the loss and improving the model’s predictions.

Role of Optimizers

Optimizers are algorithms or methods used to minimize an error function(loss function)or to maximize the efficiency of production. Optimizers are mathematical functions which are dependent on model’s learnable parameters i.e Weights & Biases. Optimizers help to know how to change weights and learning rate of neural network to reduce the losses

Common Optimizer

1. SGD (Stochastic Gradient Descent)

SGD updates each parameter based on its gradient:

2. Momentum Optimizer

The Momentum optimizer accelerates the gradient descent by considering the past gradients. The update rules are:

where γ is the momentum term.

3. NAG (Nesterov Accelerated Gradient) Optimizer

NAG is a variation of the momentum optimizer that makes a correction to the gradient by looking ahead at the future position in parameter space. Its update rules are:

4. AdaGrad Optimizer

AdaGrad adapts the learning rate to the parameters, performing smaller up-dates for frequent and larger updates for infrequent parameters. The update rule is:

where Gt is a diagonal matrix where each diagonal element i, i is the sum of the squares of the gradients w.r.t. ai up to time step t.

5. RMSprop Optimizer

RMSprop divides the learning rate for a weight by a running average of the
magnitudes of recent gradients for that weight. The update rule is:

where β is a decay rate that controls the moving average.

6. Adam Optimizer

Adam combines ideas of Momentum and RMSprop. Its update rules are:

AdamW Optimizer

The AdamW optimizer is an extension of the Adam optimizer that incorporates weight decay to mitigate overfitting. When applying L2 regularization (weight decay) to the Adam optimizer, the
AdamW Algorithm is as follows:

Source : https://arxiv.org/pdf/2302.06675.pdf

For the sake of computational efficiency, the equations for AdamW can be simplified to make them more manageable, especially when dealing with large models like LLMs and Vision Transformers.

Bias correction is essential in Adam because the values of mt and vt are initialized with zeros at the start. This initialization introduces bias, which needs to be offset.

AdamW combines the benefits of the Adam optimizer with the advantages of weight decay (L2 regularization) to mitigate overfitting. It is particularly useful for large-scale models, and the simplified equations help maintain computational efficiency.

Similar to Adam, AdamW is known for its reliability and efficiency, with no
significant issues reported in practice

Lion Optimizer : What & Why

What is AutoML?

Lion is not like other optimizers which where formulated by using some concepts like momentum or adaptive learning rates. Lion was developed using a technique known as AutoMl. The basic idea behind this technique is to find novel ML codes using ML itself. This generates loads of possible codes and then tries to figure out which one is better and hence finding a new approach from the infinite space. This starts with taking a parent code which can be some random code or some already existing good optimizer. The functions which this uses for the changes are already defined.
Now, it can make changes in this code in three ways:

  • It can introduce a new function.
  • It can introduce a new variable.
  • It can change the value of the existing function.

Using these changes, it makes children optimizers and checks if this is a better optimizer than the previous. If so, then we found a new optimizer otherwise it continues changing further. One will notice very soon that the search space is infinite and it is almost impossible for the code to find the optimal code. So, to reduce the search space, we use efficient search techniques such as:

  1. Evolution with warm-start and restart: It keeps a population of P algorithms that are gradually improved through cycles. Each cycle picks T<P algorithms at random and the best performer is chosen as the parent.
  2. Pruning through abstract execution: We prune the redundancies in the program space from three sources: programs with syntax or type / shape errors, functionally equivalent programs, and redundant statements in the programs.
  3. Proxy tasks and search cost: To reduce search cost, we create low-cost proxies by decreasing the model size, number of training examples, and steps from the target tasks.

Also, for generalization i.e. program selection and simplification, we use the following methods:

  1. Large generalization gap: The discovered algorithms face a significant challenge due to the substantial gap between the proxy tasks during search and the target tasks. Our observation suggests that evolutionary search experiments that meta-overfit later tend to uncover optimization algorithms that generalize better.
  2. Funnel selection: To mitigate the generalization gap, we collect promising programs based on search fitness and add an extra selection step using a series of meta-validation tasks to select those generalize better.
  3. Simplification: Simpler programs are easier to understand and our intuition is that they are more likely to generalize, so we simplify the programs by removing redundant statements, removing non redundant statements which have very less effect and also by manually rearranging the statements.

The Lion program defines a train function that encodes the optimization algorithm being searched for. It takes model weights (w), gradients (g), and the learning rate schedule value (lr) as inputs at the current training step and returns the update to the weights. Extra variables initialized as zeros are used to collect historical information during training.

Lion may require a smaller learning rate and a larger decoupled weight decay. The gain from Lion is more significant with larger batch sizes. However, its advantage decreases when using strong augmentations or a small batch size. Further work is needed to reduce bias in the search space and discover more novel algorithms.

Pseudo Code:

Source : https://arxiv.org/pdf/2302.06675.pdf

The Lion algorithm produces update with uniform magnitude across all dimensions by taking the sign operation, which is in principle different from various adaptive optimizers. Additionally, Lion leads to the convergence in smoother regions, which usually results in better generalization. Lion is able to balance between remembering a ∼10x longer history of the gradient in momentum and putting more weight on the current gradient in the update due to the two momentum variables. Lion is simpler and has fewer hyperparameters compared to AdamW and Adafactor as it does not require epsilon and factorization-related ones. Lion needs a smaller learning rate and in turn a larger decoupled weight decay to achieve a similar effective weight decay strength. Lion only saves the momentum thus has smaller memory footprint than popular adaptive optimizers like AdamW.

Results of Lion according to paper

Lion requires lesser learning rate as compared to adamW.
Lion usually performs better on higher batch sizes though there are some exceptions.
The lion optimizer is faster than adamW.

Press enter or click to view image in full size

Variables : Hyperparameters

Learning Rate (α): Determines the step size at each iteration.

Lambda (Weight Decay): Used in AdamW, adds a regularization term
to the loss function.

Beta1 and Beta2: In Adam and AdamW, these control the decay rates
of moving averages.

Methodology

Models Used

1. Vision Transformer (ViT)

The ViT, initially pre-trained on ImageNet-21k and fine-tuned on ImageNet
2012, uses a transformer-based method for image recognition:

  • It treats an image as a sequence of patches.
  • Applies a transformer encoder to capture global context.
  • Suitable for complex image recognition tasks.

This model represents a shift from traditional convolutional approaches to transformer based methods in image recognition.

2. Convolutional Neural Network (CNN)

The CNN model is designed for image processing and comprises:

  • Two convolutional layers (Conv2d) with increasing filter sizes.
  • A max pooling layer (MaxPool2d) for dimensionality reduction.
  • A dropout layer (Dropout2d) to prevent overfitting.
  • A fully connected layer (Linear) for classification.

This architecture is adept at extracting spatial hierarchies of features from images.

Press enter or click to view image in full size

3. Sentiment Analysis Model

This NLP model, designed for sentiment analysis, includes:

  • An Embedding Layer to convert text into dense vectors.
  • A Bidirectional LSTM Layer for capturing long-term dependencies in
    text data.
  • A Classifier for mapping LSTM outputs to sentiment categories.

The bidirectional LSTM is key for understanding context in language

Datasets

ImageNet-Sketch Dataset

This dataset includes 50,000 images, with 50 images for each of the 1,000 ImageNet classes. Compiled using Google Image queries for “sketch of [class name]” in a ”black and white” color scheme, the dataset was manually cleaned to remove irrelevant or incorrectly classified images. Augmentation was done through flipping and rotating for classes with fewer than 50 images after cleaning.

Press enter or click to view image in full size
Source : https://github.com/HaohanWang/ImageNet-Sketch

CIFAR-10

The CIFAR-10 dataset, a subset of the 80 million tiny images dataset, comprises 60,000 32x32 color images in 10 object classes, with 6,000 images per class. It was collated by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. Cited in Will Cukierski (2013), ”CIFAR-10 — Object Recognition in Images”, Kaggle.

Source : https://www.cs.toronto.edu/ kriz/cifar.html

Natural Images Dataset

The Natural Images dataset contains 6,899 images distributed across 8 different classes: airplane, car, cat, dog, flower, fruit, motorbike, and person. These images are sourced from various places and are acknowledged in the dataset’s documentation. It serves as a diverse collection for training and testing CNN models. This dataset is created as a benchmark dataset for the work on Effects of Degradations on Deep Neural Network Architectures.

Press enter or click to view image in full size
Source : https://arxiv.org/abs/1807.10108

Trip Advisor Hotel Reviews Dataset

This dataset consists of approximately 20,000 hotel reviews from Tripadvisor. It is instrumental in analyzing factors contributing to positive or negative hotel reviews. The dataset is applicable in developing hotel recommendation systems or travel planning tools. Referenced in Alam, M. H., Ryu, W.-J., Lee, S. (2016) study ”Joint multi-grain topic sentiment: modeling semantic aspects for online reviews”, Information Sciences 339, 206–223.

Press enter or click to view image in full size

Experimentation

Hyperparameter Tuning

The hyperparameter tuning is done for the natural image dataset. This is done so as to find the optimal values of the hyperparameters on which we can further run the ablations. The best values of the hyperparameters for lion are as follows:
1. Learning Rate: 0.0001
2. Weight Decay: 0.01
3. Momentum (Beta1): 0.9
4. Momentum (Beta2): 0.99

Ablations

These studies are critical in understanding how various hyper parameters affect a neural network’s learning process and overall performance. They provide insights into the fine-tuning required for optimal model functionality.

We do it so as to find the best hyperparameters and observe the effect which every parameter causes on the Optimizer.

Learning Rate Ablation

This ablation helps us to understand the effect of learning rate on the optimizer.
We did this twice. Once we did it on a large range with high gaps. This helped us to find the narrower range on which we run the ablation again but this time with much smaller gaps so as to find the exact value of best performing learning rate.

We choose the batch size as 32 for the experiments as if its too low, it will cause bias and if it too large, then there is high possibility of underfit.

Experiment1 Configuration:

Learning Rate : 1e-4, 5e-5, 5e-6, 1e-7
Batch Size : 32
Epoch: 10
Beta1 : 0.9 (Adam and Lion)
Beta2:
0.999 (Adam)
Beta2:
0.99 (Lion)
Lambda :
0.01, 0.05, 0.1, 0.2, 0.25, 1.0
Dataset:
ImageNet (Sketch)

Observation

  • We observed that 1e-7 Learning Rate is too small for Lion Optimizer in this experiement.
  • Learning Rate 0.0001 is too large and is causing

Experiment 2 : Part 1 Configuration:

Learning Rate : [0.01, 0.02, … 0.99, 1.00]
Batch Size : 32
Epoch: 20
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Lambda : 0.01
Dataset:
Natural Images Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

  • SGD performs better over a wider range of learning_rates.
  • Momemtum Optimizer is performing in a small range when the learning rate is less around 0.01.
  • AdaGrad and Adam have Adaptive Learning Rate so its performing better over a wide range.
  • Since AdamW is performing on a small range, the weight Decay required for this task seems to be high.
  • Here we verify that Lion require very small learning_rates below 0.01 (in this case) while discussing it in the earlier Section.

Experiment 2 : Part 2 Configuration:

Learning Rate : [0.0001, 0.0002, … , 0.001, 0.002 , … , 0.01, 0.02, … 0.1]
Batch Size : 32
Epochs: 40
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Lambda : 0.01
Dataset:
Natural Images Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

We are getting similar result like before:

  • SGD is performing better in wide range of learning_rates.
  • Momemtum and NAG still performing in a smaller range
  • Since AdamW is performing on a small range, the weight Decay required for this task seems to be high.
  • Since the Purple Area is more in Lion Graph so that means that Lion requires lower Learning Rate than AdamW.

Experiment 3 Configuration:

Learning Rate : [0.0001, 0.0002, … , 0.001, 0.002 , … , 0.01, 0.02, … 0.1]
Batch Size : 32
Epochs: 20
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Lambda : 0.01
Dataset:
Trip Advisor Hotel Reviews Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

Even in different Domain, there is a persistance in our observation that:

  • Lion requers less Learning Rate than AdamW.

Weight Decay Ablation

Experiments altering weight decay values and their effects on the model’s generalization capabilities and overfitting prevention, especially focusing on the AdamW and Lion optimizers.

Experiment1 Configuration:

Weight Decay : [0.01, 0.02, …, 0.09, 0.1, 0.2, … 0.9, 1.0]
Batch Size : 32
Epoch: 80
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Dataset:
Natural Images Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

We took the Best Learning rate for the respective optimizer from the prev Learning learning_rates

  • We observed that AdamW seems to be more sensitive to Weight Decay as compared to Lion.

Experiment2 Configuration:

Weight Decay : [0.01, 0.02, …, 0.09, 0.1, 0.2, … 0.9, 1.0]
Batch Size : 32
Epoch: 20
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Dataset:
Trip Advisor Hotel Reviews Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

  • We observed that with Lion Optimizer there was a drop in the accuracy at all the weight decays around 15–20 epoch.

Momentum Ablation

Experiments varying the momentum parameter, looking at how it influences the model’s convergence speed and overall performance.

Experiment1 Configuration:

Betas : [0.001, 0.002, … , 0.01, 0.02, … , 0.1, 0.2 , … , 1.00]
Batch Size : 32
Epoch: 80
Lambda : 0.01
Dataset:
Natural Images Dataset

Press enter or click to view image in full size
Momentum and RMS Prop Optimizer
Press enter or click to view image in full size
Beta 1 Ablation : Adam & AdamW
Press enter or click to view image in full size
Beta 2 Ablation : Adam & AdamW

Observation

We took the Best Learning rate, Weight_Decay for the respective optimizer from the prev Learning learning_rates

  • Momentum, RMS Prop, Adam Optimizer are performing almost in the all range
  • Lion is performing better in the lower range beta1
  • AdamW is performing better in the higher range of beta1 and there are some vallies in lower ranges
  • Adam and aAdmW are performing better in the higher range of beta2
  • Lion is performing better in the lower range of beta2 expecially around 0.999

Experiment 2 Configuration:

Beta1 : [0.8, 0.81, … , 0.99, 1.00]
Beta2 : [0.9, 0.91, … , 0.99, 0.991, … , 0.999 , 1.00]
Batch Size : 32
Epoch: 80
Lambda : 0.01
Dataset:
Natural Images Dataset

Press enter or click to view image in full size
Beta 1 : AdamW and Lion
Press enter or click to view image in full size
Beta 2: AdamW and Lion

Observation

  • Lion and AdamW are performing good in beta1 in range 0.8 to 1 and beta2 in range 0.9 to 1

Experiment 3 Configuration:

Beta1 : [0.8, 0.81, … , 0.99, 1.00]
Beta2 : [0.9, 0.91, … , 0.99, 0.991, … , 0.999 , 1.00]
Batch Size : 32
Epoch: 20
Lambda : 0.01
Dataset:
Trip Advisor Hotel Reviews Dataset

Press enter or click to view image in full size
Beta 1 : AdamW and Lion
Press enter or click to view image in full size
Beta 2: AdamW and Lion

Observation

  • Lion and AdamW are performing good in beta1 in range 0.8 to 1 and beta2 in range 0.9 to 1
  • Lion optimizer is best performing at Beta1 : 0.9 and Beta 2 : 0.99.
  • AdamW optimizer is best performing at Beta1 : 0.86 and Beta2 is any value in range [0.9 , 1].

Batch Size Ablation

Effect of varying batch sizes on image classification (using ImageNetS ketch and CIFAR−10datasets) and sentiment analysis tasks.

Experiment1 Configuration:

Batch Size : 32, 128, 512, 1024
Epoch: 30
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Lambda : 0.01
Dataset:
ImageNet-Sketch Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

  • Our Lion is performing better in smaller Batch Size when compared to AdnamW in higher Batch Size.
  • The accuracy of inbulit lion and our lion is almost the same.

Experiment2 Configuration:

Batch Size : 32, 64, 128, 256, 512, 1024, 2048, 4096
Epoch: 140
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Lambda : 0.01
Dataset:
CIFAR-10

Press enter or click to view image in full size
Press enter or click to view image in full size
Inbuilt AdamW and Inbuilt Lion
Press enter or click to view image in full size

Observation

  • The observation we got is that with the increase with batch Size, the accuracy of Lion over AdamW improves. This validates the statements given in the original Lion Paper.

Experiment2 Configuration:

Batch Size : 32, 128, 512, 1024
Epoch: 40
Beta1 : 0.9 (Adam and Lion)
Beta2: 0.999 (Adam)
Beta2: 0.99 (Lion)
Lambda : 0.01
Dataset:
Trip Advisor Hotel Reviews Dataset

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

  • As given in the lion paper, we see that lion performs better on higher batch size than in higher batch size in AdamW.
  • The accuracy of inbulit lion and our lion is almost the same.

Model Architecture Ablation

Effect of CNN and liner layers on image classification.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Observation

  • There isn’t much different in the performance of AdamW and Lion as when the number of parameters was incresed with 2–3x times of parameter — We suspect Weight Decay to be its reason)
  • As we increase the number of parameter as in model2 , it overfits on the training the data and the validation accuracy decreases.
  • But as we normalize in model 3, the overfitting reduces thus increasing the validation accuaray again.

Loss Landscapes : Lion Vs AdamW

Here, we try to make loss landscapes on some loss functions to try to visualize how Lion and AdamW traverse over them.

Loss Function 1

Press enter or click to view image in full size

This image shows the loss landscape of the above function.

Press enter or click to view image in full size

Parameters:
Learning Rate (LR): 0.02
Limit (LIMIT): 0.5
Gamma (GAMMA): 0.9
Beta1 (BETA1): 0.9
Beta2 (BETA2): 0.95
Lambda (LAMBDAA): 10^−8
Initial Parameters (init_params): [4,3.5]

Get Yash Bhaskar’s stories in your inbox

Join Medium for free to get updates from this writer.

Number of Epochs:
Lion Optimizer: 485
AdamW Optimizer: 611

Press enter or click to view image in full size

Parameters:
Learning Rate (LR): 0.001
Limit (LIMIT): 0.1
Gamma (GAMMA): 0.9
Beta1 (BETA1): 0.9
Beta2 (BETA2): 0.95
Lambda (LAMBDAA): 10^−8
Initial Parameters (init_params): [4,3.5]

Number of Epochs:
Lion Optimizer: 7198
AdamW Optimizer: 7296

Observations

Here, from first 2 plots we infer that since we use sign function in the lion optimizer, hence,we get very sharp turns in each epoch while this is not the case for adamW.
The reason why both of them cross the turn point is momentum. Since, adamW changes the learning rate, so the distance travelled is lesser while it is more in lion. In the 2nd plot we see that as we decrease the learning rate, even lion doesn’t go a long way ahead of the turning point.

Press enter or click to view image in full size
Press enter or click to view image in full size

Here, in the above 2 plots, we can see the square wave pattern of the lion
clearly near the convergence point.

Loss Function 2

Following plot shows the loss landscape of the above function:

Press enter or click to view image in full size

Number of Epochs:
Lion Optimizer: 20000
Adam Optimizer: 575

Observations

The number of lion is so high as it doesn’t reduce the loss to the threshold value but the loss is very less but always greater than the cut off. This might also be due to the sign function as it always overshoots the lowest loss value.

Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 0.01
LIMIT: 0.01
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 10^−8
init_params: [6,5.5]

Number of Epochs:
Lion Optimizer: 20000
AdamW Optimizer: 575

Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 0.1
LIMIT: 0.01
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [6,5.5][6,5.5]

Number of Epochs:
Lion Optimizer: 20000
AdamW Optimizer: 206

Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 1
LIMIT: 0.01
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [6,5.5][6,5.5]

Number of Epochs:
Lion Optimizer: 20000
AdamW Optimizer: 173

Observations

In the above three plots, we see that lion is very sensitive for the learning
rate while adamW is much better in this respect as it has adaptive learning rates. As we increase the learning rate, the lion slowly starts to fail to reach
the minima and is all over the place while adamW still manages to reach the minima much more efficiently.

Loss Function 3

This is the loss curve for the above function.

Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 1
LIMIT: 0.01
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [6,5.5][6,5.5]

Number of Epochs:
Lion Optimizer: 7
Adam Optimizer: 7

Observations

Here we notice that the seed of lion of traversing down the loss curve is
higher than the adamW. An explaination to this can also be given using the
fact that adamW has adaptove learning rates.

Loss Function 4

This is the loss curve for the above function.

Press enter or click to view image in full size
Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 0.001
LIMIT: 0.0001
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [1.57,2][1.57,2]

Number of Epochs:
Lion Optimizer: 17290
Adam Optimizer: 1428

Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 0.001
LIMIT: 0.01
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [1.57,2][1.57,2]

Number of Epochs:
Lion Optimizer: 1356
Adam Optimizer: 1389

Observations

Here, we notice the same thing we did earlier that due to the sign function, lion tends to jump over the minimum loss again and again and thus traversing a large distance while adamW doesn’t. But as we decrease the learning rate, the lion finds the minimum loss value and thus preventing overshooting. This also proves the point that lion is very sensitive to the learning rate.

Loss Function 5

Press enter or click to view image in full size

The above plot shows the loss landscape of the above function.

Parameters for the Above Plot:
LR: 0.1
LIMIT: 0.01
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [6,5.5][6,5.5]

Number of Epochs:
Lion Optimizer: 20000
Adam Optimizer: 89

Observations

Here it is easy to notice that lion skips the first minima and goes to the other one while adamW remains in the first one. This is again due to adaptive learning rate of AdamW optimizer. This property of lion is helpful as it can skip the local minima and it is more probable to find global minima.

Loss Function 6

This plot shows the loss curve for the above function

Press enter or click to view image in full size

Parameters for the Above Plot:
LR: 1
LIMIT: 0.0001
GAMMA: 0.9
BETA1: 0.9
BETA2: 0.95
LAMBDAA: 1×10−81×10−8
init_params: [6,5.5][6,5.5]

Number of Epochs:
Lion Optimizer: 2
Adam Optimizer: 2

Observations

Here, we try to see the difference between lion and adam if the loss is constant.

Here one other observation is that the number of epochs taken by lion is always lesser than the number of epochs taken by adam. This is visible in the graph below. It is made using the values given above.

Conclusion

The main observations we got are:

  1. The learning rate required for Lion is lesser than any other optimizer and that lion is very sensitive to the learning rate used.
  2. Lion optimizer has a drop in accuracy after about 15–20 epochs in weight decay ablation.
  3. We find that the values of optimal betas for AdamW and lion given in the paper give high accuracies and thus are the best values.
  4. We also find that Lion usually performs better on higher batch sizes though there are some exceptions.
  5. We also found that lion traverses the loss curve in squary pattern due to the sign function.
  6. It has a chance of missing the absolute minima while it is always very close to the actual minima.
  7. Lion has a better momentum velocity as compared to AdamW and thus it has a higher chance to find the global minimum while the other can get stuck in a local minima.
  8. Lion starts off with a higher speed than the AdamW optimizer as adamW changes its learning rate and decreases it as the gradient of the loss decreases.
  9. Lion is faster than AdamW i.e. it has higher convergence rate.

References

@article{roy2018effects, title={Effects of Degradations on Deep Neural Network Architectures}, author={Roy, Prasun and Ghosh, Subhankar and Bhattacharya, Saumik and Pal, Umapada}, journal={arXiv preprint arXiv:1807.10108}, year={2018}}

@inproceedings{wang2019learning, title={Learning Robust Global Representations by Penalizing Local Predictive Power}, author={Wang, Haohan and Ge, Songwei and Lipton, Zachary and Xing, Eric P}, booktitle={Advances in Neural Information Processing Systems}, pages={10506–10518}, year={2019}}

Vision Transformer, 🚀99.5% Accuracy + ⚡ Embedding | Kaggle

👍👎Sentiment Analysis Using Pytorch | Kaggle

Appexdix

Inroduction To Neural Nets

In the world of machine learning, neural networks have established themselves as a formidable tool. They power various applications, from simple image classification tasks to natural language processing task like Text Classification. While their capabilities are vast, these models often come with high computational costs, both in terms of training time and inference. As such, any strategy that can speed up training without compromising accuracy is a boon to researchers and practitioners.

One such avenue of optimization lies in the initialization of the weights of the neural network. Proper weight initialization can lead to quicker convergence during training, which in turn reduces the required computational resources and time.

Optimizers

One of the most popular machine learning (ML) tools is a neural net, which can be applied to a wide range of tasks like face recognition, sentiment analysis, image categorization, and much more.

Extensive neural networks, such as Large Language Models made up of many Transformers Encoder and Decoder Blocks, are sometimes quite large (parameter-wise), computationally demanding, and need a lot of time (both during training and inference). Therefore, methods for enhancing these neural nets’ performance must be discovered.

The pace of training is the fundamental component that is discussed while discussing the model’s performance. A faster training rate leads to a better model performance. Enhancing the model’s performance indicates that we are attempting to arrive at the lowest loss value as quickly as feasible; therefore, reaching an even lower loss value would be the icing on the cake.

The most basic techniques of improving the performance of the Neural Network are:

  1. Weight Initialization
  2. Batch normalization
  3. Activation Function

Weight Initialization

Zero initialization:

Consider a simple experiment: a neural network is designed with three hidden layers. Each layer uses a ReLU activation function, except the output layer which deploys a sigmoid function. To begin, every weight and bias in the network is initialized to zero. After training the model for 15,000 iterations, the resulting loss stands at 0.6931471805599453, corresponding to an accuracy of merely 50%.

From this, it’s evident that initializing all weights to zero isn’t conducive for effective training. When weights are all set to zero, neurons in the network become symmetric during forward and backward passes. This means every neuron in a given layer will learn the same features during training, which defeats the purpose of having multiple neurons in the first place.

In the context of deep learning, this is analogous to having a single neuron per layer, drastically reducing the capacity of the model. Therefore, while zero initialization seems straightforward, it’s not a productive approach for neural network training.

Source : https://towardsdatascience.com/weight-initialization-techniques-in-neural-networks-26c649eb3b78

Random initialization

It is preferable to assign random values to weights rather than just 0. One
item to consider, though, is what would happen if weights were initially set
to extremely high or low amounts, and what would constitute an appropriate initialization of weight values.

The term np.dot(W,X)+b increases noticeably if weights are started with extremely high values. Similarly, using an activation function such as sigmoid() causes the function to map its value close to 1,
where the gradient’s slope varies slowly and learning takes a long time. When weights are initialized with small values, they are mapped to 0, in which case the preceding scenario applies. This problem is often referred to as the vanishing gradient. To illustrate this, let’s look at the example we used previously, only this time the weights are initialized with very big values rather than 0:

W [l] = np.random.randn(l-1,l)*10.

Source : https://towardsdatascience.com/weight-initialization-techniques-in-neural-networks-26c649eb3b78

Using the same neural network as before and this initialization on the ”make circles” dataset from sklearn.datasets, the following outcome was obtained: for 15000 iterations, loss = 0.38278397192120406, accuracy = 86%

Batch Normalization

The process of normalizing a dataset’s numerical variable’s value to a typical scale without distorting contrasts within the range of values is known as normalization. Batch normalization normalizes the contributions to a layer for each mini-batch. This results in
stabilizing the learning process and significantly reducing the number of training epochs required to train deep neural networks.

Why Batch Normalization is required in deep learning:
Training a deep neural network with numerous layers is crucial in deep learning. These networks can be sensitive to the initialization of weights and the design of the learning algorithm. The distribution of inputs to deeper layers may change after each mini-batch update, leading to a constantly shifting target. This change in input distribution is termed as “internal covariate shift.” Given that the weights in preceding layers are fixed and estimated using error approximation, it becomes challenging to sequentially update each layer.
Batch normalization can reparameterize almost any deep neural network,
which considerably alleviates the problem of updating several layers simultaneously.

How is Batch Normalization Done:
Batch normalization aims to normalize activations within mini-batches to improve training stability and speed.
By keeping the mean at zero and the standard deviation at one, it ensures a consistent input distribution across layers. This method can be applied to a
variety of networks and offers regularization benefits.

Activation Function

Definition: It determines the output of a neural network. The resulting values are mapped between specific ranges, e.g., 0 to 1 or -1 to 1, depending on the function.

Activation Functions can be divided into:
1. Linear Activation Function: It’s linear, so the output won’t be con-
fined using a Linear activation Function.
2. Non-linear Activation Functions: These are the most commonly used
functions, enabling the model to adapt and differentiate outputs.

Training Challenges

Despite these techniques, achieving a significant performance boost remains a challenge. Two primary challenges include:

  • Oscillations and Slow Convergence: It can result when the learning
    rate is too high.
  • Convergence to Local Minima: It occurs when the optimization process finds local minima that aren’t the global minimum, leading to sub-
    optimal performance.
Press enter or click to view image in full size
IIIT H — SMAI : Lecture

Optimizers in Deep Learning

Improving model performance is contingent on addressing the training issues with deep neural networks. Here are the intricacies:

  1. Learning Rate Selection: The learning rate is crucial. Incorrect values
    can lead to locking in local minima, slow convergence, or overshooting.
    Optimizers like Adam offer adaptive learning rates
  2. Learning Rate Scheduling: The learning rate can be dynamically ad-
    justed. RMSprop and AdaGrad are examples that adjust based on previ-
    ous gradients.
  3. Non-Uniform Learning Rates: Not all parameters converge at the
    same rate. Optimizers can customize learning rates for each parameter.
  4. Saddle Points and Local Minima: They can obstruct convergence to
    the global minimum. Techniques like L-BFGS and SGD with momentum
    can navigate these regions.

But even with these techniques, the performance increase is not high and as greedy as we are, we strive for better performance.

Optimizers

Here, we try to explain and compare 8 different kinds of optimizers, namely:

SGD Optimizer

The most popular optimisation technique in deep learning and machine learning is gradient descent. The algorithm for optimisation is of the first order. This indicates that when it does the parameter changes, it only considers the first derivative. The gradient of the objective function J(w) with respect to the parameters indicates the direction of the steepest climb, and we update the parameters in the opposite direction for each iteration. The learning rate α dictates the amount of the step we take on each iteration to reach the local minimum. Thus, until we arrive at a local minimum, we proceed downhill in the slope’s direction. Firstly, let us examine the operation of gradient descent on logistic regression and then discuss the specifics of its variations.

Momentum Optimizer

Momentum optimizer is a significant improvement over the Stochastic Gradient Descent (SGD) optimizer. It is based on the concept of exponentially weighted moving averages, which is a crucial component of its functioning.
Exponentially weighted moving averages (EWMA) are used to calculate the
average of a sequence of values while giving more weight to recent values. In the context of gradient descent, this means that the momentum optimizer keeps track of an exponentially weighted moving average of past gradients to adapt the current gradient update.
The mathematical formulation for calculating the exponentially weighted
moving average at each iteration is as follows:

Where:

— vt is the exponentially weighted moving average at iteration t.
— vt−1 is the previous exponentially weighted moving average.
— gt is the gradient at iteration t. — β is the momentum parameter (a hyperparameter usually set between 0 and 1).
Now, let’s delve into how momentum optimizer addresses several issues encountered in training neural networks

Benefits of Momentum Optimizer

  1. High Curvature: Momentum helps in situations where the loss landscape has regions with high curvature. When the gradient consistently points in a certain direction (either positive or negative), the momentum term accumulates, causing the optimizer to move faster in that direction. This helps the models escape steep and narrow valleys more efficiently.
  2. Consistent Gradients: In cases where gradients are consistent over
    several iterations, the exponentially weighted moving average ensures that the optimizer maintains a high velocity in the same direction. This persistence in movement enables the model to converge faster.
  3. Noisy Gradients: Noisy gradients can lead to erratic updates in stan-
    dard SGD. Momentum helps smooth out these variations by considering the history of gradients. It prevents the model from getting distracted by noise, resulting in a more stable convergence.

Core Idea of Momentum

The core idea behind momentum in the context of deep learning is inspired by the concept of momentum in physics. When an object has a positive velocity for an extended period, it gains momentum and continues to move in the same direction. Similarly, in momentum optimization, if the gradient consistently has the same sign (positive or negative) over several iterations, the model accumulates momentum in that direction and moves faster.
This concept is realized through the exponentially weighted moving aver-
age, which incorporates information from previous gradients. The formula for updating the exponentially weighted moving average is as follows:

Where:

— vt is the updated moving average at iteration t. — vt−1 is the previous
moving average.

— gt is the gradient at iteration t.

— β is the momentum
parameter.
The use of past gradient information allows the optimizer to gain momentum and move faster in the direction indicated by the majority of past gradients.
This increases the chances of the optimizer reaching the global minima, as it can escape local minima.

Challenges of Momentum Optimizer

However, momentum optimizer is not without its challenges. It can sometimes overshoot the global minima and get stuck in local minima. Additionally, the momentum can cause oscillations around the minima, which can lead to slower convergence and an increased number of epochs required to reach the minima.

The oscillations can be mitigated by using a well-tuned learning rate and
adjusting the momentum parameter (β).

NAG Optimizer

The Nesterov Accelerated Gradient (NAG) optimizer is designed to address
the issue of slow convergence and overshooting encountered by the Momentum optimizer. It achieves this by modifying the way it computes the gradient updates, resulting in faster convergence and reduced overshooting.

Core Idea of NAG

In the Momentum optimizer, in each epoch, we move ahead with the speed
of the momentum plus gradients, which can lead to significant overshooting over the minima. NAG takes a different approach to reduce this overshooting.
It first takes a momentum step, essentially an estimate of where the current momentum will take us, and then calculates the gradient at the new point. The actual gradient update is determined based on this new gradient information. Mathematically, NAG computes the momentum step as follows:

Where:

— ̃vt is the momentum step at iteration t.
— β is the momentum parameter.

Then, it calculates the gradient at the new point (with the momentum step):

Where: — ̃gt is the gradient at the new point. — ∇f (θ − ̃vt) is the gradient of the loss function at the new point (θ − ̃vt).
The actual update is then determined based on this new gradient informa-
tion:

Where: — θt+1 is the updated parameter at iteration t + 1. — θt is the current
parameter. — α is the learning rate. — ̃gt is the gradient at the new point.

Tradeoff

The NAG optimizer introduces a tradeoff. While it decreases the number of
epochs required to reach a minimum, it may increase the likelihood of getting stuck at local minima due to its modified approach. This tradeoff should be carefully considered when choosing an optimization algorithm for training a neural network.

AdaGrad Optimizer

The term ”AdaGrad” is derived from ”Adaptive Gradients.” The core idea be-
hind this optimizer is to adapt the learning rate for each feature during training, aiming to optimize the learning process.

Problem of Sparse Features

AdaGrad is particularly beneficial when dealing with sparse datasets, where certain features have different gradients and learning rates are not uniform across all features. If a uniform learning rate is used, it can lead to two issues:
1. Low Learning Rate: If the learning rate is set too low to prevent the
model from diverging significantly from a local minimum for one feature, it can result in a slow convergence rate, requiring a high number of epochs to reach the minimum.
2. High Learning Rate: On the other hand, if the learning rate is set
high, it may allow faster convergence for a different feature, but it can cause significant deviation from the local minimum of another feature.

AdaGrad Formulation

AdaGrad is the first optimizer that adapts the learning rate for each feature
during each epoch. This adaptation is achieved through the following formula:

Where: — θt+1,i is the updated parameter for feature i at iteration t + 1. -
θt,i is the current parameter for feature i. — α is the global learning rate. — Gt,i is the accumulated squared gradient for feature i up to iteration t. — ε is a small constant to avoid division by zero. — gt,i is the gradient of the loss function with respect to feature i at iteration t.
The core idea of AdaGrad is to make the learning rate inversely proportional to the square root of the accumulated squared gradients. This ensures that if a particular feature has a high gradient (i.e., Gt,i is high), the learning rate for that feature will be decreased to prevent overshooting. Conversely, if the gradient is low, the learning rate will be increased, allowing faster convergence.

Challenges of AdaGrad

While AdaGrad offers adaptive learning rates, it has a notable issue. After a
certain point in training, the accumulated squared gradients (Gt,i) become large, leading to excessively small learning rates. This can eventually make further convergence impossible, preventing the optimizer from reaching a solution.

RMSprop Optimizer

RMSprop, short for Root Mean Squared Propagation, is an improvement over the AdaGrad optimization technique. It addresses the challenges of AdaGrad while maintaining adaptive learning rates.

RMSprop Formulation

In RMSprop, the key difference from AdaGrad is the use of a decaying weighted mean average of the squared gradients, which prevents the learning rate from vanishing. The formulas for RMSprop are as follows:

Where: — E[g2]t is the decaying weighted mean of squared gradients at iter-
ation t. — β is the decay rate, typically close to 1 but less than 1. — g2
t is the squared gradient at iteration t. — θt+1 is the updated parameter at iteration t + 1. — θt is the current parameter. — α is the learning rate. — ε is a small constant to avoid division by zero. — gt is the gradient of the loss function at iteration t.

Advantages of RMSprop

RMSprop successfully overcomes the major issue of vanishing learning rates experienced in AdaGrad. By using a decaying weighted mean of squared gradients, it ensures that the learning rate doesn’t reach zero. This adaptability in learning rates enables the optimizer to reach the minimum loss point efficiently.
One of the significant advantages of RMSprop is that it effectively addresses the challenges of AdaGrad, such as overly aggressive learning rate decay.

Challenges

Unlike AdaGrad, RMSprop does not suffer from the issue of vanishing learning rates. Hence, it is considered a more stable optimizer with no major issues.

Adam Optimizer

Adam, which stands for ADaptive Moment Estimation, is an optimizer that
combines the principles of both momentum and RMSprop, resulting in efficient and adaptive learning rates.

Adam Formulation

The mathematical formulation of the Adam optimizer is as follows:

Where: — mt is the first moment estimate (like momentum) at iteration t.
- vt is the second moment estimate (like RMSprop) at iteration t. — ˆmt is the
bias-corrected first moment estimate. — ˆvt is the bias-corrected second moment estimate. — β1 and β2 are the exponential decay rates, typically close to 1 but less than 1. — gt is the gradient of the loss function at iteration t. — θt+1 is the updated parameter at iteration t + 1. — θt is the current parameter. — α is the global learning rate. — ε is a small constant to avoid division by zero. — t is the current iteration.

Bias Correction

Bias correction is essential in Adam because the values of mt and vt are initialized with zeros at the start. This initialization introduces bias, which needs to be offset. The bias-corrected moments, ˆmt and ˆvt, are calculated to adjust for this bias, ensuring more accurate estimates over time.

Advantages of Adam

Adam is advantageous as it combines the benefits of both momentum and RMSprop, offering an efficient and adaptive learning rate. It typically converges faster and is widely used in various deep learning applications.

No Major Issues

Unlike some other optimization techniques, Adam is known for its reliability and efficiency, with no significant issues reported in practice.

Dataset Description

The dataset used for this experiment is the Trip Advisor Hotel Reviews dataset, which comprises approximately 20,000 hotel reviews extracted from Tripadvisor.
This dataset is useful for understanding what aspects contribute to a positive or negative hotel review and can be applied in a practical context for hotel recommendation systems or travel planning assistance. The dataset was referenced in the following study:
Alam, M. H., Ryu, W.-J., Lee, S., 2016. Joint multi-grain topic sen-
timent: modeling semantic aspects for online reviews. Information
Sciences 339, 206–223

Model Architecture Used:

  1. CNN Based Image Classification
Press enter or click to view image in full size
CNN Based Image Classification

Net(
(conv1): Conv2d(3, 12, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(conv2): Conv2d(12, 24, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(drop): Dropout2d(p=0.2, inplace=False)
(fc): Linear(in_features=24576, out_features=10, bias=True)
)

This architecture includes two convolutional layers (conv1 and conv2), a max-pooling layer (pool), a dropout layer (drop), and a fully connected layer (fc).
The first convolutional layer takes an input with 3 channels (representing RGB images) and produces 12 output channels, while the second convolutional layer increases the depth from 12 to 24. The max-pooling layer is used to reduce the spatial dimensions of the output from the convolutional layers. The dropout layer is included to prevent overfitting by randomly setting a fraction of input units to 0 at each update during training. The fully connected layer maps the features learned by the convolutional and pooling layers to the final output classes

2. BiLSTM based Sentiment Analysis

Press enter or click to view image in full size
Source : https://www.researchgate.net/figure/The-BiLSTM-used-in-the-text-
classification fig2 341687263

The Sentiment Analysis model used in these experiments comprises several key components:

  • Embedding Layer: This layer converts input text, represented as token
    indices, into dense vectors of fixed size. In our model, this layer takes
    the total vocabulary size and the desired embedding dimension as inputs, creating an embedding for each word in the
  • BiLSTM Layer: The Long Short-Term Memory (LSTM) layer is a type of
    recurrent neural network that is capable of learning long-term dependencies in sequence data. Our model uses a bidirectional LSTM, which means it processes the data in both forward and backward directions, capturing information from past and future states.
  • Classifier: After processing the sequence data through the LSTM layer,
    the output is passed to a classifier. This component is a linear layer that
    maps the output of the LSTM to the desired number of output classes,
    which correspond to different sentiment categories in our case.
    The model is designed to first transform the raw text into embeddings, which are then processed by the LSTM to capture the contextual relationships within the text. Finally, the classifier determines the sentiment of the review based on the features extracted by the LSTM.

3. VIT Base 12 (Vision Transformers)

The Vision Transformer (ViT) model architecture is a deep learning model designed for computer vision tasks. It differs from traditional Convolutional Neural Networks (CNNs) by utilizing self-attention mechanisms inspired by the Transformer model, originally developed for natural language processing. ViT splits an input image into fixed-size non-overlapping patches, which are then linearly embedded into sequences. These sequences are processed through a stack of Transformer encoder layers to capture global and local features from the image.

CoAuthor : https://medium.com/@harshitaggarwal2627

--

--

Yash Bhaskar
Yash Bhaskar

Written by Yash Bhaskar

Kaggle GrandMaster | Applied Scientist Amazon | AI-ML Researcher | Freelance Expert | DM on LinkedIn to collaborate! linkedin.com/in/yash-bhaskar