Stable Adam Optimization for 16-bit Neural Networks Training
In this research, we address critical concerns related to the numerical
instability observed in 16-bit computations of machine learning models. Such
instability, particularly when employing popular optimization algorithms like
Adam, often leads to unstable training of deep neural networks. This not only
disrupts the learning process but also poses significant challenges in
deploying dependable models in real-world applications. Our investigation
identifies the epsilon hyperparameter as the primary source of this
instability. A nuanced exploration reveals that subtle adjustments to epsilon
within 16-bit computations can enhance the numerical stability of Adam,
enabling more stable training of 16-bit neural networks. We propose a novel,
dependable approach that leverages updates from the Adam optimizer to bolster
the stability of the learning process. Our contributions provide deeper
insights into optimization challenges in low-precision computations and offer
solutions to ensure the stability of deep neural network training, paving the
way for their dependable use in various applications.
Juyoung Yun
Trustworthy Optimization: A Novel Approach to Counter Numerical Instability in 16-bit Neural Network Training

###### Abstract

In this research, we address critical trustworthiness concerns related to the numerical instability observed in 16-bit computations of machine learning models. Such instability, particularly when employing popular optimization algorithms like RMSProp and Adam, often leads to unreliable training of deep neural networks. This not only disrupts the learning process but also poses significant challenges in deploying dependable models in real-world applications. Our investigation identifies the epsilon hyperparameter as the primary source of this instability. A nuanced exploration reveals that subtle adjustments to epsilon within 16-bit computations can enhance the reliability of RMSProp and Adam, enabling more trustworthy training of 16-bit neural networks. We propose a novel, dependable approach that leverages updates from the Adam optimizer to bolster the stability of the learning process. Our contributions provide deeper insights into optimization challenges in low-precision computations and offer solutions to ensure the trustworthiness and stability of deep neural network training, paving the way for their dependable use in various applications.

## 1 Introduction

The meteoric advancement of machine learning and artificial intelligence technologies has enabled the construction of neural networks that effectively emulate the complex computations of the human brain. These deep learning models have found utility in a wide range of applications, such as computer vision, natural language processing, autonomous driving, and more. With the growing complexity and sophistication of these neural network models, the computational requirements, particularly for 32-bit operations, have exponentially increased. This heightened computational demand necessitates the exploration of more efficient alternatives, such as 16-bit operations.

However, the shift to 16-bit operations is riddled with challenges. A common standpoint within the research community argues that 16-bit operations are not ideally suited for neural network computations. This belief is mainly attributable to concerns related to numerical instability during the backpropagation phase, especially when popular optimizers like Adam [8] and RMSProp [15] are employed. This instability, more pronounced during the optimizer-mediated backpropagation process rather than forward propagation, can negatively impact the performance of 16-bit operations and compromise the functioning of the neural network model. Current optimizers predominantly operate on 32-bit precision. If these are deployed in a 16-bit environment without appropriate hyperparameter fine-tuning, the neural network models encounter difficulties during learning. This issue is particularly evident in backward propagation, which heavily relies on the optimizer. Confronted with these challenges, the objective of this research is to conduct an exhaustive investigation into the feasibility and implementation of 16-bit operations for neural network training. We propose and
evaluate innovative strategies aimed at reducing the numerical instability encountered during the backpropagation phase under 16-bit environments. A significant focus of this paper is also dedicated to exploring the future possibilities of developing 16-bit based optimizers. One of the fundamental aims of this research is to adapt key optimizers such as RMSProp and Adam to prevent numerical instability, thereby facilitating efficient 16-bit computations. These newly enhanced optimizers are designed to not only address the issue of numerical instability but also leverage the computational advantages offered by 16-bit operations, all without compromising the overall performance of the neural network models. Through this research, our intention goes beyond improving the efficiency of neural network training; we also strive to validate the use of 16-bit operations as a dependable and efficient computational methodology in the domain of deep learning. We anticipate that our research will contribute to a shift in the prevalent perceptions about 16-bit operations and will foster further innovation in the field. Ultimately, we hope our findings will pave the way for a new era in deep learning research characterized by efficient, high-performance neural network models.

## 2 Related Works

The matter of numerical precision in deep learning model training has garnered substantial attention in recent years. A milestone study by Gupta et al. [4] was among the first to explore the potential of lower numerical precision in deep learning, emphasizing the critical balance between computational efficiency and precision. They suggested that with careful implementation, lower precision models can be as effective as their higher precision counterparts while requiring less computational and memory resources. Building upon these findings, significant advancements have been made in utilizing 16-bit operations for training convolutional neural networks. Courbariaux et al. [2] pioneered a novel technique to train neural networks using binary weights and activations, significantly reducing memory and computational demands. Despite these advancements, numerical instability during backpropagation remains a persistent challenge. Bengio et al. [1] illustrated the difficulties encountered in learning long-term dependencies with gradient descent due to numerical instability. Such findings underscore the need for innovative solutions to mitigate this widespread issue. One critical component to addressing this challenge lies in the development of effective optimizers. Adam, an optimizer introduced by Kingma and Ba [8], is known to face issues of numerical instability when employed in lower-precision environments. In the context of efficient neural network training, Han et al. [5] proposed a three-stage pipeline that significantly reduces the storage requirements of the network. Their work forms an integral part of the broader discussion on efficient neural network training, further reinforcing the relevance of our research on 16-bit operations. Through our investigation, we aim to contribute to this body of work by presenting a novel approach to addressing numerical instability issues associated with 16-bit precision in the realm of deep learning model training. **Mixed Precision Training**: Micikevicius et al. [12] stressed the imperative transition from 32-bit to 16-bit operations in deep learning, given the memory and computational constraints associated with training increasingly complex neural networks. Their research demonstrated that mixed precision computations offer a more memory and computation-efficient alternative without compromising the model's performance. Another research by Yun et al. [16], provided a comprehensive theoretical analysis, focusing on the performance of pure 16-bit floating-point neural networks. They introduced the concepts of floating-point error and tolerance to define the conditions under which 16-bit models could approximate their 32-bit counterparts. Their results indicate that pure 16-bit floating-point neural networks can achieve similar or superior performance compared to their mixed-precision and 32-bit counterparts, offering a unique perspective on the benefits of pure 16-bit networks.

## 3 Analysis

Through theoretical analysis, we analyze which part of the neural network occurs numerical instability which can ruin the training process.

### Forward Propagation

**Linear Network.** During forward propagation, each column of the input matrix \(X\) represents a distinct training example. This matrix layout simplifies the network's computation, as each feature of
every training sample can be processed in parallel, exploiting the parallel nature of matrix operations.

\[X=\begin{bmatrix}x_{11}&x_{12}&\cdots&x_{1m}\\ x_{21}&x_{22}&\cdots&x_{2m}\\ \vdots&\vdots&\ddots&\vdots\\ x_{n1}&x_{n2}&\cdots&x_{nm}\end{bmatrix}\]

The weight matrix \(W\) represents the strength and direction of connections between neurons. Each column of \(W\) corresponds to the set of weights connecting every input neuron to a specific hidden neuron.

\[W=\begin{bmatrix}w_{11}&w_{12}&\cdots&w_{1k}\\ w_{21}&w_{22}&\cdots&w_{2k}\\ \vdots&\vdots&\ddots&\vdots\\ w_{n1}&w_{n2}&\cdots&w_{nk}\end{bmatrix}\]

The bias vector \(b\) provides an additional degree of freedom, allowing each neuron in the hidden layer to be activated not just based on weighted input but also based on this inherent property.

\[b=\begin{bmatrix}b_{1}\\ b_{2}\\ \vdots\\ b_{k}\end{bmatrix}\]

The raw outputs or pre-activations (denoted as \(Z\)) are computed by multiplying the transposed weight matrix with the input matrix and adding the bias.

\[Z=W^{T}X+b\]

After computing \(Z\), we need a mechanism to introduce non-linearity into our model. Without this, no matter how deep our model, it would behave just like a single-layer perceptron. This non-linearity is introduced using an activation function \(\sigma(\cdot)\), applied element-wise to the matrix \(Z\).

\[A=\sigma(Z)\]

Here, each entry \(a_{ij}\) in \(A\) is the activated value of the \(j\)-th neuron in the hidden layer when the model is provided the \(i\)-th training example. These activations will either be used as input for subsequent layers or be the final output of the network.

In Deep Neural Network (Linear Network.), each operation in the forward pass involves straightforward mathematical operations like addition and multiplication. There is no division or complex operation that could amplify small numerical errors or lead to potential instability.

**Convolutional Network.** In the realm of deep learning, especially when processing image data, CNNs have gained significant prominence. The foundational blocks of CNNs involve convolving filters over input data and pooling layers [11].

The convolution layer can be detailed by observing the element-wise multiplication and summation [11]. Specifically, in our 3x3 input matrix \(I\) and 2x2 filter \(F\) example:

\[I=\begin{bmatrix}i_{11}&i_{12}&i_{13}\\ i_{21}&i_{22}&i_{23}\\ i_{31}&i_{32}&i_{33}\end{bmatrix}\qquad\qquad\qquad\qquad F=\begin{bmatrix}f_{ 11}&f_{12}\\ f_{21}&f_{22}\end{bmatrix}\]

For the top-left corner of \(I\), the convolution operation using the filter \(F\) is as follows:

\[o_{11}=\begin{bmatrix}i_{11}&i_{12}\\ i_{21}&i_{22}\end{bmatrix}\odot\begin{bmatrix}f_{11}&f_{12}\\ f_{21}&f_{22}\end{bmatrix}\]

Where \(\odot\) represents element-wise multiplication. This implies:

\[o_{11}=i_{11}\cdot f_{11}+i_{12}\cdot f_{12}+i_{21}\cdot f_{21}+i_{22}\cdot f _{22}\]

The filter \(F\) continues sliding across \(I\), performing similar computations for each position, resulting in the matrix:

\[O=\begin{bmatrix}o_{11}&o_{12}\\ o_{21}&o_{22}\end{bmatrix}\]
Each element in the output matrix \(O\) is computed in the same fashion, with each \(o_{ij}\) being the result of convolving a 2x2 segment of \(I\) with the filter \(F\).

Pooling layers can also be represented using matrix notation, though the operation is simpler. For max pooling with a 2x2 window, given an input matrix \(I\), the operation for a single position can be illustrated as [9]:

\[P_{ij}=\max\begin{bmatrix}I_{2i-1,2j-1}&I_{2i-1,2j}\\ I_{2i,2j-1}&I_{2i,2j}\end{bmatrix}\]

For an example 4x4 input matrix being processed by a 2x2 max pooling operation:

\[I=\begin{bmatrix}i_{11}&i_{12}&i_{13}&i_{14}\\ i_{21}&i_{22}&i_{23}&i_{24}\\ i_{31}&i_{32}&i_{33}&i_{34}\\ i_{41}&i_{42}&i_{43}&i_{44}\end{bmatrix}\]

The output matrix \(P\) from this max pooling operation will be:

\[P=\begin{bmatrix}\max(i_{11},i_{12},i_{21},i_{22})&\max(i_{13},i_{14},i_{23}, i_{24})\\ \max(i_{31},i_{32},i_{41},i_{42})&\max(i_{33},i_{34},i_{43},i_{44})\end{bmatrix}\]

In CNNs, actions taken during the forward pass primarily consist of basic arithmetic, such as addition and multiplication. There's an absence of division or intricate calculations that might magnify minor numerical inaccuracies or trigger potential instability.

Especially those with a significant number of layers, the iterative multiplications during forward propagation can intermittently lead to either vanishingly small values or notably large increments in the activations. However, methods such as batch normalization[7] have been introduced to regulate and prevent these activations from attaining extreme values. Therefore, forward propagation, which involves the transmission of input data through the network to produce an output, is generally more resilient to such instabilities. This comparative robustness can be ascribed to a variety of underlying reasons:

* Simplified Operations: Forward propagation predominantly involves elementary mathematical operations such as addition and multiplication. Thus, the results are less prone to reaching extreme values unless the input data or model parameters are improperly scaled or exhibit a high dynamic range [6].
* Absence of Derivatives: Contrasting backpropagation, forward propagation does not necessitate the computation of derivatives, a process that could engender exceedingly large or small numbers, thus inducing numerical instability [14].
* Limited Propagation of Errors: Forward propagation is less likely to accumulate and propagate numerical errors throughout the network. This contrasts with backpropagation, where errors could proliferate through the derivative chain [11].

### Backward Propagation

We focused on backpropagation rather than forward propagation. The reason for this is that forward propagation consists of the product and sum of the matrix without division operations. In pursuit of a thorough mathematical scrutiny, our objective pivots on three principal tenets: firstly, to dissect and understand the operational intricacies of each optimizer; secondly, to pinpoint the exact circumstances and causes that give rise to numerical instability; and finally, to formulate effective solutions that can aptly mitigate these issues. To exemplify, consider the update rule in the gradient descent method for optimizing a neural network [13]:

\[\theta=\theta-\eta\nabla_{\theta}J(\theta)\]

In this equation, \(\theta\) denotes the parameters of the model, \(\eta\) represents the learning rate, and \(\nabla_{\theta}J(\theta)\) signifies the gradient of the loss function \(J(\theta)\) with respect to the parameters. Understanding such equations allows us to uncover the internal mechanics of each optimizer, thereby facilitating our quest to alleviate numerical instability.
### Mini-Batch Gradient Descent

Mini-batch gradient descent is a variant of the gradient descent algorithm that divides the training datasets into small batches to compute errors [13]. The update rule for the parameters in mini-batch gradient descent can be written as:

\[\theta= \theta-\eta\nabla_{\theta}J(\theta;x^{(i:i+n)};y^{(i:i+n)})\]

This optimizer leverages mini-batches of \(m\) examples \((x^{(i:i+n)},y^{(i:i+n)})\) from the training dataset \(x^{(i)},...,x^{(n)}\) to update the model's parameters \(\theta\in\mathbb{R}^{d}\). It aims to minimize the loss function \(J(\theta)\) by taking calculated steps that are antithetical to the gradient of the function with respect to the parameters [13]. The magnitude of these steps is dictated by the learning rate, denoted by \(\eta\). It is postulated that Mini-Batch Gradient Descent can function optimally in a 16-bit environment, given the limited number of hyperparameters that can provoke numerical instability within the neural network during the process of minimizing \(J(\theta)\).

* **Assumption 3.1**_Consider the input image data \(x\in Xx_{1},\dots,x_{i}\), the label \(y\in Yy_{1},\dots,y_{i}\), where each \(x\in\mathbb{R}\) satisfies \(0<x<255\), and each \(y\in\mathbb{Z}\). The normalized data \(\bar{x}\) will lie in the range \(0.0<\bar{x}<1.0\). If \(fp16_{min}<f(x,y)=\nabla_{\theta}J(\theta;x^{(i)};y^{(i)}))<fp16_{max}\), and \(f(x,y)\) does not engender numerical instability \(I=NaN,Inf\) during the update of \(\theta\), it can be deduced that the mini-batch gradient descent method will function properly for training the 16-bit neural network._

Based on _Assumption 3.1_, the number of hyperparameters in the Mini-Batch Gradient Descent that could instigate numerical instability is restricted. Consequently, we anticipate that this optimizer should function efficiently within a 16-bit neural network with default hyperparameters.

### RMSProp

Root Mean Square Propagation, more commonly referred to as RMSProp, is an optimization methodology utilized in the training of neural networks. This technique was proposed by Geoff Hinton during his Coursera class in Lecture 6e [15]. However, when implemented within a 16-bit neural network using default hyperparameters, RMSProp results in the model weights turning into \(NaN\), thereby causing a complete halt in the training process. Figure 1 shows that when training MNIST with a 16-bit neural network using RMSProp, the weights become NaN (white points) after a few epochs if a value less than 1e-4 is used as epsilon. To circumvent this numerical problem, it is essential to understand the source of numerical instability that RMSProp introduces in 16-bit environments. The update rule for RMSProp can be expressed as follows:

\[w_{t}= w_{t-1}-\eta\frac{g_{t}}{\sqrt{v_{t}}+\epsilon}\]

The 16-bit floating-point representation has a more constrained computational scope in contrast to the 32-bit variant. When values exceed or fall below the valid range of \(fp16\), numerical instability emerges during the training sequence. In the context of the RMSProp optimizer, the learning rate \(\eta\) typically doesn't instigate issues provided \(\eta>fp16_{min}\). However, the denominator \(v_{t}\), adaptive learning rate, and \(\epsilon\) can trigger numerical instability if their values extend beyond the allowable range.

\[v_{t}= \begin{cases}0&if\ v_{t}<fp16_{min}\\ \beta v_{t-1}+(1-\beta)g_{t}{}^{2}&otherwise\\ \infty&if\ v_{t}>fp16_{max}\end{cases}\]

If the value of \(v_{t}\) falls below \(fp16_{min}\), \(v_{t}\) converges to zero, which in turn affects \(w_{t}\). The expression for \(w_{t}\) can then be rearranged so that only \(\epsilon\) remains in the denominator. Under these circumstances, the numerical instability of the optimizer is primarily induced by the default \(\epsilon\) value. In TensorFlow, the default value for \(\epsilon\) is set to 1e-07, and the default learning rate \(\eta\) is configured as 1e-03.

\[w_{t}= w_{t-1}-\eta\cdot g_{t}\cdot\epsilon^{-1}\]
The adjustment of weights is contingent upon the \(\epsilon\) value. Nevertheless, during this process, numerical instability may emerge when this value is inversed, leading to underflow and overflow incidents in the optimizer.

\[\epsilon^{-1}= \begin{cases}\infty&if\ \epsilon^{-1}>fp16_{Max}\\ \epsilon^{-1}&otherwise\end{cases}\]

Should the value of epsilon decline to 1e-07, its reciprocal soars to 1e+07. While the 16-bit format accommodates 1e-07, it cannot handle 1e+07, leading to an overflow that escalates to \(\infty\). This overflow is an inevitable outcome, independent of \(g_{t}\), the gradient's value. The progressive unfolding of such overflow instances stirs up numerical instability, eventually compromising the integrity of the neural network. Whenever \(\epsilon^{-1}>fp16_{max}\), the term \(g_{t}\cdot\epsilon^{-1}\) will invariably result in \(I=\infty,-\infty\), contingent on the sign of \(g_{t}\).

\[w_{t}= \begin{cases}w_{t-1}-\infty&if\ g_{t}>0\\ w_{t-1}+\infty&if\ g_{t}<0\end{cases}\]

The current weight is represented by \(w_{t}=w_{t-1}-i\ (i\in I)\) which yields \(NaN,-\infty\) when \(w_{t-1}\in\infty,-\infty\). Upon the occurrence of \(NaN\), this optimizer ceases to function on a 16-bit neural network, a consequence of the TensorFlow default epsilon setting being at 1e-07.

* **Assumption 3.2**_We posit that the input image data \(x\in Xx_{1},\ldots,x_{i}\) and label \(y\in Yy_{1},\ldots,y_{i}\), where all \(x\in\mathbb{R}\), \(0<x<255\), and all \(y\in\mathbb{Z}\). The normalized data \(\bar{x}\) will lie within the range of \(0.0<\bar{x}<1.0\). Similarly, the gradient \(g_{t}\) will fall within the range \(fp16_{min}<g_{t}<fp16_{max}\). There exist two conditions under which RMSProp can operate effectively in a 16-bit environment. Firstly, if \(v_{t}\neq 0\), \(v_{t}\geq fp16_{min}\) and \(fp16_{min}<\sqrt{v_{t}}+\epsilon<fp16_{max}\), \(w_{t}\) will not undergo \(overflow\). Secondly, when

Figure 1: Evolution of neural network weights across 20 epochs with RMSProp optimizer. The plot displays the weights of the first Dense layer in the Deep Neural Network with MNIST Dataset. The x-axis represents the first 10 input neurons, the y-axis shows the first 32 neurons of the ’Dense1’ layer, and the depth (z-axis) indicates the training epochs. Colors, based on the ’RdBu’ colormap, denote the magnitude and direction of the weight. We used le-2 as learning rate and TensorFlow for this.
\(v_{t}<fp16_{min}\), \(v_{t}\) becomes \(0\). In this case, if \(g_{t}\cdot\epsilon^{-1}<fp16_{max}\), RMSProp successfully evades critical numerical instability. Provided either of these conditions are met, the RMSProp optimizer will function appropriately in a 16-bit neural network._

In the event that _Assumption 3.2_ holds true, the RMSProp optimizer is capable of executing effectively in 16-bit neural networks. An improper selection of the epsilon parameter could misdirect the course of learning in the 16-bit neural network, potentially causing numerical instability. This may lead to erroneous conclusions regarding the compatibility of the RMSProp optimizer with 16-bit neural networks.

### Adam

Adam is a sophisticated optimization algorithm that amalgamates the salient features of the RMSProp and Momentum methods. Conceived by Diederik Kingma and Jimmy Ba, the Adam optimizer implements the technique of adaptive moment estimation to iteratively refine neural network weight calculations with enhanced efficiency [8]. By extending stochastic gradient descent, Adam optimally addresses non-convex problems at an accelerated pace, requiring fewer computational resources compared to a host of other optimizers. The potency of this algorithm is particularly noticeable when dealing with large datasets, as it maintains a tighter trajectory over numerous training iterations.

\[w_{t}= w_{t-1}-\eta\cdot\frac{\hat{m}_{t}}{\sqrt{\hat{v}_{t}}+\epsilon}\]

Figure 1 shows that when training MNIST with a 16-bit neural network using Adam, the weights become NaN (white points) after a few epochs if a value less than 1e-3 is used as epsilon. When considering the Adam optimizer, numerical instability arises following principles akin to those governing RMSProp. However, an additional distinguishing element in Adam is the introduction of a momentum variable, \(m\). In the Adam optimizer, both \(m\) and \(v\) are initialized to zero. Hence, at the

Figure 2: Evolution of neural network weights across 20 epochs with Adam optimizer. The plot displays the weights of the first Dense layer in the Deep Neural Network with MNIST Dataset. The x-axis represents the first 10 input neurons, the y-axis shows the first 32 neurons of the ’Dense’ layer, and the depth (z-axis) indicates the training epochs. Colors, based on the ’RdBu’ colormap, denote the magnitude and direction of the weight. We used le-2 as learning rate and TensorFlow for this.
onset of learning, both \(m_{t}\) and \(v_{t}\) are inclined towards zero, undergoing an initial process to remove this bias.

\[m_{t}= \beta_{1}\cdot m_{t-1}+(1-\beta_{1})\cdot g_{t}\] \[v_{t}= \beta_{2}\cdot m_{t-1}+(1-\beta_{2})\cdot{g_{t}}^{2}\]

The velocity variable \(v_{t}\) in the Adam optimizer is a non-negative real number. The adjusted velocity \(\hat{v}t\) is calculated as the ratio of \(v_{t}\) to \((1-\beta 2)\). Therefore, if \(v_{t}\) is less than the maximum value permissible in 16-bit floating point precision, \(fp16_{max}\), then \(\hat{v}_{t}\) will approach zero. This condition significantly influences the calculated value of \(w_{t}\) within the Adam optimizer.

\[w_{t}= w_{t-1}-\eta\cdot\hat{m_{t}}\cdot\epsilon^{-1}\]

In the event where the inverse of epsilon (\(\epsilon^{-1}\)) exceeds the maximum value permissible in a 16-bit floating point (\(fp16_{max}\)), \(\epsilon^{-1}\) essentially becomes infinite. The default value of \(\epsilon\) in TensorFlow is \(1e-07\), while the default learning rate (\(\eta\)) is \(1e-03\). Therefore, if \(\epsilon\) is \(1e-07\), its reciprocal escalates to infinity. Depending on the sign of the adjusted momentum (\(\hat{m_{t}}\)), the value of \(\eta\cdot\hat{m_{t}}/\epsilon\) will either be positive or negative infinity. Consequently, irrespective of the learning rate \(\eta\), \(\hat{m_{t}}/\epsilon\) will belong to the set \(I=\infty,-\infty\). As a result, the new weight update equation \(w_{t}=w_{t-1}-i\) (\(i\in I\)) leads to a situation where \(w_{t}\) belongs to the set \(NaN,-\infty\) whenever \(w_{t-1}\) is \(\infty,-\infty\). This introduces numerical instability in the learning process.

\[w_{t}= \begin{cases}w_{t-1}-\infty&if\;\hat{m_{t}}>0\\ w_{t-1}+\infty&if\;\hat{m_{t}}<0\end{cases}\]

This process induces a numerical instability in a 16-bit neural network. In particular, if the previous weight \(w_{t-1}\) is \(-\infty\), the operation \(w_{t-1}\) - \(\infty\) returns \(-\infty\), but \(w_{t-1}\) + \(\infty\) produces a non-numeric value (\(NaN\)). Consequently, the current weight \(w_{t}\) becomes \(NaN\), thereby halting training within the 16-bit Neural Network utilizing the Adam optimizer.

* **Assumption 3.3** posits that the input image data \(x\in Xx_{1},\ldots,x_{i}\), label \(y\in Yy_{1},\ldots,y_{i}\), where all \(x\in\mathbb{R}\) satisfy \(0<x<255\), and all \(y\in\mathbb{Z}\). The normalized data \(\bar{x}\) from \(x\) will lie in the range \(0.0<\bar{x}<1.0\), and the momentum \(m_{t}\) will fall within \(fp16_{min}<m_{t}<fp16_{max}\). Two conditions may allow the Adam optimizer to function in a 16-bit setting. Primarily, if \(\hat{v_{t}}\neq 0\), \(\hat{v_{t}}\geq fp16_{min}\) and \(fp16_{min}<\sqrt{\hat{v_{t}}}+\epsilon<fp16_{max}\), the weight \(w_{t}\) will not overflow. Additionally, when \(\hat{v_{t}}<fp16_{min}\), \(\hat{v_{t}}\) becomes \(0\). If \(\hat{m_{t}}\cdot\epsilon^{-1}<fp16_{max}\), the Adam optimizer circumvents critical numerical instability. Provided one of these conditions is met, the Adam optimizer functions effectively in a 16-bit neural network.

Given that the Adam optimizer incorporates the method of the RMSProp optimizer, similar issues impede its performance in a 16-bit Neural Network. However, if Adam satisfies _Assumption 3.3_, the optimizer can function within a 16-bit Neural Network. Proper comprehension and handling of the epsilon issue enables the utilization of a variety of optimizers even within 16-bit computations.

Our exploration into the root causes of numerical instability has led us to a singularly intriguing finding - the value of the hyperparameter, Epsilon, plays a remarkably pivotal role. This discovery, though unassuming at first glance, has far-reaching implications in our quest for numerical stability within the realm of neural network optimization. Epsilon is often introduced in the denominator of certain equations to prevent division by zero errors or to avoid the pitfalls of numerical underflow. In the context of optimizers such as RMSProp and Adam, it's usually involved in the update rule, safeguarding against drastic weight changes arising from exceedingly small gradient values. However, in a 16-bit computational environment, when the reciprocal of Epsilon becomes larger than the maximum representable number, it leads to a condition known as numerical overflow. The overflow subsequently manifests as numerical instability, disrupting the otherwise orderly progression of the learning process, and effectively halting the training of the 16-bit neural network.

**Epsilon.** Consider the function \(f(x)=\frac{1}{x}\). As \(x\) nears 0, \(f(x)\) grows indefinitely. By adding \(\epsilon\) (i.e., \(f(x)=\frac{1}{x+\epsilon}\)), the function remains bounded near 0. In optimization, this ensures parameter updates stay bounded, aiding numerical stability during training. However, in low precision scenarios, the
presence of \(\epsilon\) can induce instability, as gradients become overshadowed by this constant. This isn't unique to the Adam optimizer and adjusting Epsilon's value isn't straightforward, with its ideal value often being context-specific. We've developed a method to address this, offering a systematic approach to Epsilon tuning, ensuring stable optimization amidst numerical challenges.

## 4 Method

### Existing Method

**Loss Scaling in Mixed Precision**: Mixed precision training [12] is a technique that utilizes both 16-bit and 32-bit floating-point types during training to make it more memory efficient and faster. However, the reduced precision of 16-bit calculations can sometimes lead to numerical underflow, especially in the intermediate gradient values in some optimizers such as Adam and RMSProp. To prevent this, the "loss scaling" method is employed. Loss scaling is a straightforward concept. Before performing backpropagation, the loss is scaled up by a large factor. This artificially increases the scale of the gradients and thus helps prevent underflow. After the gradients are calculated, they are scaled back down to ensure the weights are updated correctly. In essence, this process amplifies the small gradient values to make them representable in the reduced precision and then scales them back down to ensure that the actual model updates remain accurate. While mixed precision does use 16-bit calculations, it leans on 32-bit calculations for the critical parts to maintain accuracy, especially for maintaining running sums and optimizer states. This implies that we aren't fully exploiting the speed and memory benefits of 16-bit precision. According to Table 1, Mixed precision based VIT-16 will not reduce GPU memory usage because it utilizes 32-bit computation for mixed precision.

Contrary to the mixed precision method, a pure 16-bit neural network operates entirely in the 16-bit precision realm. There are several reasons why pure 16-bit computations can outshine both 32-bit and mixed precision. First, 16-bit operations are faster than their 32-bit and mixed precision. Second, 16-bit representations require half the memory of 32-bit, which means we can fit larger models or batch sizes into GPU memory, further enhancing performance. Yun et at[16] shows pure 16-bit neural networks are faster than both 32-bit and mixed precision. This means that mixed precision with loss scaling method cannot utilize advantages of 16-bit operations. The inefficiencies and the constant juggling between 16-bit and 32-bit in mixed precision, along with the need for methods like loss scaling, indicate that a more robust solution is needed for numerical stability in low precision environments. This is where the "Numerical Guarantee Method" comes into play. Instead of hopping between precisions or artificially scaling losses, the Numerical Guarantee Method aims to provide a stable environment for optimizers like Adam to function efficiently in pure 16-bit computations. This approach makes the training process faster and potentially more accurate than using 32-bit or mixed precision models.

### Numerical Guarantee Method

In this study, we present a novel approach designed to alleviate numerical instability, a common problem associated with widely-used optimizers such as Adam and RMSProp, in the training of 16-bit neural networks. These optimizers have frequently encountered challenges when working with smaller epsilon values, particularly in instances involving division operations. The genesis of our method stems from an in-depth mathematical exploration of the update rules in the Adam optimizer, which revealed that instability originates during the gradient update step - a phase where the momentum term (\(\hat{m}\)) is divided by the sum of the square root of the velocity term (\(\hat{v}\)) and the epsilon parameter (\(\epsilon_{t}\)). To circumvent this instability, we propose a refined version of the gradient computation equation, which effectively prevents division by an exceedingly small epsilon value.

\begin{table}
\begin{tabular}{c c c c c} \hline \hline  & Epsilon & Test Accuracy & Training Time (seconds) & GPU Memory Usage \\ \hline Floating Point 16-bit & 1E-3 & 0.686 & 1255.35 & 1.234 GB \\ Floating Point 32-bit & 1E-3 & 0.693 & 1733.14 & 2.412 GB \\ Mixed Precision (MP) & 1E-3 & 0.685 & 1430.12 & 2.415 GB \\ \hline \hline \end{tabular}
\end{table}
Table 1: Performance comparison between 16-bit, 32-bit, and Mixed Precision settings for training VIT-16[3] with cifar-10 images and Adam optimizer.
This is achieved by introducing a maximum function that sets a lower threshold on the denominator. Consequently, the updated Adam optimizer follows the equation:

\[w_{t}=w_{t-1}-\frac{\eta\cdot\hat{m}_{t}}{\sqrt{\max(\hat{v}_{t},\epsilon)}}\]

The modification guarantees that the denominator remains within a safer numerical range, thus facilitating a more stable gradient update. The addition of the stabilizing term, \(\sqrt{\max(\hat{v}_{t},\epsilon)}\), ensures the denominator does not dwindle excessively, thereby avoiding abnormally large updates. Should \(\hat{v}_{t}\) fall below \(\epsilon\), the term assumes the square root of \(\epsilon\) instead. The precise value employed as the lower limit (in this case, \(\epsilon\) is 1e-4) can be tailored according to the specific requirements of the neural network in consideration. Our proposed adjustment to the Adam optimizer offers a myriad of benefits, which are elaborated upon subsequently:

* Enhanced Numerical Stability: By taking the maximum of \(\hat{v}_{t}\) and a small constant inside the square root function, we mitigate the numerical instability that arises when \(\hat{v}_{t}\) is very close to zero. This enhancement significantly reduces the chances of overflow and underflow during computations, which in turn increases the robustness of the optimizer.
* Preservation of Adam's Benefits: The modification does not alter the fundamental characteristics and benefits of the Adam optimizer. It retains the benefits of Adam, such as efficient computation, suitability for problems with large data or parameters, and robustness to diagonal rescale or translations of the objective functions.
* Ease of Implementation: The modification requires just a minor change to the original Adam algorithm, making it easy to implement in practice. This simplicity of modification allows for easy integration into existing machine learning frameworks and pipelines, thereby increasing its accessibility to practitioners.
* Applicability to 16-bit Computations: The updated method enables Adam to work effectively on 16-bit neural networks, which was a challenge with the original Adam optimizer due to numerical instability issues. Thus, it extends the applicability of Adam to systems and applications where memory efficiency is crucial.
* Flexibility: This modification is generalizable and can be applied to other optimizers based on the same concept as Adam, thereby providing a broad range of applications.

Overall, these advantages make this modification an effective solution to the problem of numerical instability in Adam and similar optimizers, particularly in the context of 16-bit computations. Our approach presents a novel way to alleviate numerical instability in 16-bit neural networks, without losing the advantages offered by advanced optimizers such as Adam and RMSProp. We will demonstrate the effectiveness of our approach through comprehensive experimental results in the following section.

## 5 Results

Our first experimental setup was comprised of a deep neural network (DNN) with 3 linear layers trained on the MNIST dataset [11], a ubiquitous benchmark in the field of machine learning, to evaluate the performance of two widely adopted optimization algorithms: RMSProp [15] and Adam [8]. The network was implemented using the TensorFlow framework, and a batch size of 512 was utilized during the training process. The architecture of the DNN was relatively simple, containing a single linear layer, which provided a streamlined environment to assess the relative merits of the two optimization strategies. The results of the performance comparison between the RMSProp and Adam optimizers under different precision settings are summarized in Table 2.

Our second experiment focuses on the Vision Transformer (ViT)[3], a complex and sophisticated image training model. The Vision Transformer (ViT) was originally introduced and benchmarked using the Adam optimizer in the foundational paper by Dosovitskiy et al. [3]. In their experiments, Adam was chosen for training the ViT on large datasets like ImageNet. The authors demonstrated that with Adam and the specific training regimen described in the paper, the ViT model achieves
competitive performance compared to state-of-the-art convolutional networks. Therefore, we had empirical experiments about VITs with adam optimizer incorporating with numerical guarantee method. Specifically, we employed variants of the ViT model, including ViT-8, ViT-12, and ViT-16, to train on the CIFAR-10 image dataset[10]. The performance of the Adam optimizer under various precision settings, when used with these ViT models (with no data augmentation) and trained in 100 epochs, is summarized in Table 3. These findings are detailed as follows:

### 16-bit Precision with Numerical Guarantee

In the realm of 16-bit precision, the integration of numerical guarantee methods--highlighted as 'O' in Table 2--led both RMSProp and Adam optimizers to consistently achieve stellar test accuracies, all surpassing the \(0.98\) mark. This commendable performance was evident across various epsilon values, underscoring the robust numerical stability even when working within precision-constrained environments. As for time efficiency, disparities were minimal: RMSProp took an estimated \(98\) to \(100\) seconds per training epoch, while Adam hovered around \(110\) seconds. Table 3 reveals that the 16-bit vision transformer models fortified with our numerical guarantee technique align closely with

\begin{table}
\begin{tabular}{c c c c c c c} \hline \hline \multicolumn{1}{c}{} & \multicolumn{2}{c}{**Numerical**} & \multicolumn{2}{c}{**RISPProp**} & \multicolumn{2}{c}{**RISPProp**} & \multicolumn{2}{c}{**Adam**} & \multicolumn{2}{c}{**Adam**} \\ \hline
**Precision** & **epsilon** & **Guarantee Method** & **Test Accuracy** & **Training Time (seconds)** & **Test Accuracy** & **Training Time (seconds)** \\ \hline

[MISSING_PAGE_POST]

 \hline \hline \end{tabular}
\end{table}
Table 2: Performance comparison between RMSProp and Adam optimizers in 16-bit and 32-bit precision settings for training DNN.

\begin{table}
\begin{tabular}{c c c c c c c c} \hline \hline \multicolumn{1}{c}{} & \multicolumn{2}{c}{**Numerical**} & \multicolumn{2}{c}{**VIT-8**} & \multicolumn{2}{c}{**VIT-12**} & \multicolumn{2}{c}{**VIT-16**} & \multicolumn{2}{c}{**VIT-16**} \\ \multicolumn{1}{c}{} & \multicolumn{2}{c}{**Equilion**} & \multicolumn{2}{c}{**Guarantee**} & \multicolumn{2}{c}{**Test**} & \multicolumn{2}{c}{**Training Time**} & \multicolumn{2}{c}{**Test**} & \multicolumn{2}{c}{**Training Time**} \\ \multicolumn{1}{c}{} & \multicolumn{2}{c}{**Method**} & \multicolumn{2}{c}{**Accuracy**} & \multicolumn{2}{c}{(seconds)} & \multicolumn{2}{c}{**Accuracy**} & \multicolumn{2}{c}{(seconds)} & \multicolumn{2}{c}{**Accuracy**} & \multicolumn{2}{c}{(seconds)} \\ \hline

[MISSING_PAGE_POST]

 \hline \hline \end{tabular}
\end{table}
Table 3: Performance comparison of the Vision Transformer (ViT) based on 16-bit and 32-bit precision with Adam optimizer, incorporating the novel numerical guarantee method.
their 32-bit VIT counterparts in test accuracy. They possess a distinct edge, completing training at a pace that's briskly 30% swifter than the 32-bit variants across all VIT iterations.

### 16-bit Precision without Numerical Guarantee

In scenarios where the numerical guarantee was not enforced (indicated by 'X' in Table 2, 3), a decline in test accuracy was observed for both RMSProp and Adam optimizers when the epsilon value decreased below \(10^{-3}\). Despite this decline in accuracy, the computation times were relatively stable, with minor increases compared to the cases where numerical guarantees were incorporated. This shows our observation about risk of epsilon for optimizer is true.

### 32-bit Precision without Numerical Guarantee

Within the 32-bit precision domain, both the RMSProp and Adam optimizers sustained consistent test accuracies, even without the application of numerical guarantees. However, a conspicuous surge in computational time was observed when juxtaposed with the 16-bit precision settings: the RMSProp optimizer's duration spanned from \(180.59\) to \(183.81\) seconds, while the Adam optimizer's span fell between \(202.72\) to \(205.10\) seconds. As corroborated by Table 3, all VIT models operating in 32-bit exhibited a computational pace that lagged approximately 30% behind their 16-bit counterparts, irrespective of the incorporation of the numerical guarantee method.

The experiments were conducted on laptop GPUs featuring RTX 3080. An intriguing observation was that 16-bit computations were at least 40 percent faster than their 32-bit counterparts. This advantage of computational speed underlines the potential of utilizing 16-bit precision, particularly in contexts with constrained computing resources such as laptops. This study successfully establishes the critical role of numerical guarantee methods in maintaining high levels of accuracy, particularly in lower precision settings. It also emphasizes the trade-off between numerical stability and computational efficiency. While higher precision settings may be less prone to numerical instability, they demand significantly more computational resources.

To summarize, our research offers a novel approach to mitigate numerical instability in 16-bit neural networks without sacrificing accuracy. This contribution holds the potential to stimulate further advancements in the field of machine learning, particularly in applications where computational resources are limited. The findings underscore the importance of careful consideration of numerical precision in the implementation of deep learning models and highlight the potential advantages of lower-precision computations. Further investigations would be beneficial to validate these findings in more other deep learning models, such as transformers for natural language processing which is not for image classification.

## 6 Discussion

The novel approach for mitigating numerical instability presented in this work has demonstrated promising results with respect to the backpropagation phase of deep learning models when dealing with the vision transformer models. Our modification to the gradient computation equation within the Adam optimizer ensures that the denominator stays within a safe range, thereby providing a stable update for the gradient. This has the potential to significantly enhance the stability of the training process, and by extension, the accuracy of the resultant model. However, as in all scientific studies, this work is not without its limitations. The empirical validation of our proposed method has been conducted with image classification model such as the vision transformer models. While this forms the basis for more complex architectures, it remains only one part of training of the wide array of layers and structures currently utilized in modern deep learning architectures. Specifically, future research should aim to validate the robustness and utility of our approach across a broader spectrum of deep learning architectures. In particular, Transformer models for Natural Language Processing is a significant portion of the current deep learning landscape, particularly in language-related tasks. The complexity of these models, with their intricate hierarchies and highly non-linear transformations, may pose additional challenges that are not fully encapsulated by a Linear Layer. As such, it is imperative that further validation is conducted on these architectures to establish the generalizability of our method. Furthermore, while our focus has primarily been on mitigating numerical instability, it would also be beneficial to investigate any potential side effects this approach might have on
other aspects of the model training process. For instance, it would be interesting to explore the implications for training time, memory requirements, and robustness to variations in hyperparameters. In conclusion, this work presents an exciting step forward in the pursuit of more robust and stable training methodologies for deep learning models. The road ahead, while challenging, is filled with opportunities for further innovation and refinement.

## 7 Conclusions

In the realm of deep learning, achieving trustworthiness and reliability is paramount, especially when the field faces persistent challenges like numerical instability. Our research introduces a groundbreaking strategy designed to bolster the trustworthiness of neural networks, which is most evident during backpropagation processes. By innovatively tweaking the gradient update mechanism in the Adam optimizer, we've effectively curtailed the prevalent instability issues encountered in 16-bit neural training. Empirical tests leveraging the MNIST dataset with a rudimentary DNN underscored the superiority of our optimizer, frequently outclassing the conventional Adam setup in a 16-bit environment. Impressively, our trustworthy 16-bit methodology managed to truncate training durations by approximately 45% relative to its 32-bit counterpart, simultaneously preserving stability across an array of epsilon magnitudes. Further experiments on the Vision Transformer model for the cifar-10 dataset substantiated the enhanced trustworthiness of our approach: our 16-bit models processed data at a rate 30% swifter than the 32-bit models while ensuring heightened stability. Nonetheless, our investigations were primarily concentrated on image classification through Linear DNN and VIT. Anticipating future endeavors, we aim to delve into the reliability and trustworthiness of our strategy when applied to intricate architectures and diverse tasks, including NLP. Our overarching ambition is to architect a holistic solution to combat numerical instability in deep learning, and we're confident that our current contributions establish a robust groundwork for ensuing advancements in ensuring model trustworthiness.
