Adaptive Binary-Ternary Quantization
Ryan Razani Grégoire Morin Vahid Partovi Nia Eyyüb Sari


























Adaptive Binary-Ternary Quantization
    Ryan Razani, Grégoire Morin,  Eyyüb Sari, and Vahid Partovi Nia 

Huawei Noah's Ark Lab 

ryan.razani@huawei.com

    
=====================================================================================================================



empty



   Neural network models are resource hungry. It is difficult to deploy such deep networks on devices with limited resources, like smart wearables, cellphones, drones, and autonomous vehicles. Low bit quantization such as binary and ternary quantization is a common approach  to alleviate this resource requirements. Ternary quantization provides a more flexible model and outperforms binary quantization in terms of accuracy, however doubles the memory footprint and increases the computational cost. Contrary to these approaches, mixed quantized models allow a trade-off between accuracy and memory footprint. In such models, quantization depth is often chosen manually, or is tuned using a separate optimization routine. The latter requires training a quantized network multiple times. Here, we propose an adaptive combination of binary and ternary quantization, namely Smart Quantization (SQ), in which the quantization depth is modified directly via a regularization function, so that the model is trained only once. Our experimental results show that the proposed method adapts quantization depth successfully while keeping the model accuracy high on MNIST and CIFAR10 benchmarks.





§ INTRODUCTION


Deep Neural Network (DNN) models have achieved tremendous attraction due to their success on a wide variety of tasks, including computer vision, automatic speech recognition, natural language processing, and reinforcement learning <cit.>. More specifically, in computer vision DNN have led to a series of breakthrough for image classification <cit.>, <cit.>, <cit.>, and object detection <cit.>, <cit.>, <cit.>. DNN models are computationally intensive and require large memory to store the model parameters. Computation and storage resource requirement becomes the main obstacle to deploy such models in many edge devices due to lack of memory, computation power, energy, etc.  This motivated the researchers to develop compression techniques to reduce the cost for such models.

Recently, several techniques have been introduced in the literature to solve the storage and computational limitations of the edge devices. Among them, quantization methods focus on representing the weights of a neural network in lower precision than the usual 32-bits float representation, saving on the memory footprint of the model. Binary quantization <cit.>, <cit.>, <cit.>, <cit.>, <cit.>, <cit.> represent weights with 1 bit precision and ternary quantization <cit.>, <cit.>, <cit.> with 2 bits precision. While the latter frameworks lead to significant memory reduction compared to their full precision counterpart, they are constrained to quantize the model with 1 bit or 2 bits, on demand. We relax this constraint, and present Smart Quantization (SQ) that allows adapting layers to 1 bit and 2 bits while training the network. Consequently, this approach automatically quantizes weights into binary or ternary depending upon a trainable control parameter. We show that this approach leads to mixed bit precision models that beats ternary networks both in terms of accuracy and memory consumption. Here we only focus on quantizing layers because it is more feasible to implement layer-wise quantization at inference time after training. However, this method can be also adapted for mixed precision training of sub-network, block, filter, or weight.




§ RELATED WORK

There are two main components in DNN models, namely, weights and activations. These two components are usually computed in full precision, i.e. floating point 32-bits. This work focuses on quantizing the weights of the network, i.e. generalizing  BinaryConnect (BC) <cit.> and Ternary Weight Network (TWN) <cit.> toward automatic 1 or 2 bits mixed-precision using a single training algorithm. 

In BC <cit.>, the real value weights, w, are binarized to w^b∈{-1,+1} during the forward pass. To map a full precision weight to a binary weight, the deterministic sign function is used,

    w^b = sign(w) = 
    
    	+1     w≥ 0,
    
    	-1     w < 0.

The derivative of the sign function is zero on ℝ∖{0}. The sign function has zero gradient which freezes weight updates during back-propagation. To bypass this problem, BC <cit.> uses a clipped straight-through estimator 

    ∂Ł/∂ w = ∂Ł/∂ w^b1_|w| ≤ 1(w)
 
where Ł is the loss function and 1_A(.) is the indicator function on the set A. In other words (<ref>) approximates the sign function by the linear function f(x) = x within [-1, +1] and a constant elsewhere. During back propagation, the weights are updated only within [-1,+1]. The binarized weights are updated with their corresponding full precision gradients. XNOR-Net <cit.> adds a scaling factor to reduce the gap between binary and full-precision model's accuracy, defining Binary Weight Network (BWN). The real value weights  in each layer are quantized as μ×{ -1, +1 } where μ = 𝔼[||] ∈ℝ. DoReFa-Net <cit.> generalizes the latter work and approximates the full precision weights with more than one bit, while ABCNet <cit.> approximates weights with a linear combination of multiple binary weight bases. 



 §.§ Ternary weight networks 


Ternary Weight Network (TWN) <cit.> is a neural network with weights constrained to {-1,0,+1}. The weight resolution is reduced from 32 bits to 2 bits, replacing full precision  weights with ternary weights. TWN aims to fill the gap between full precision and binary precision weight. Compared to binary weight networks, ternary weight networks are more expressive. In  3×3 weight filter in a convolutional neural network, there are 2^3 × 3=512 possible variations with binary precision and 3^3 × 3=19683 with ternary precision. 

TWN <cit.> finds the closest ternary weights matrix ^t to its corresponding real value weight matrix  using

    {[                μ̂, ^t=  _μ, ^t‖W-μW^t‖^2_2,; s.t. μ≥ 0, w^t_ij∈{-1,0,1},  i,j=1,2,...,n. ].

The ternary weight ^t is achieved by applying a symmetric threshold Δ

    ^t = 
      
        +1    w_ij > Δ,
    
        0     	 |w_ij| ≤Δ,
    
        -1    w_ij < -Δ.

One may adopt a weight-dependant threshold Δ and a scaling factor μ that approximately solves (<ref>).   Similar to BC and BWN schemes; ternary-value weights are only used for the forward pass and back propagation, but not for the parameter updates. At inference, the scaling factor can be folded with the input  as,


    ⊙≈⊙ (μ^t)= (μ) ⊙^t,

where ⊙ denotes the convolution. 


Trained Ternary Quantization (TTQ) <cit.> proposes a more general ternary method which reduces the precision of weights in neural network to ternary values. However, TTQ quantizes the weights to asymmetric values {-μ_1, 0, +μ_2} using two full-precision scaling coefficients μ_1 and μ_2 for each layer of neural network.  Consequently, the method achieves better accuracy as opposed to TWN.

Note that μ is regarded as a scaling factor when the network is quantized,  during training, within a certain structure (e.g., per layer, per filter, per channel). Varying μ per weight may end up canceling the ternary simplification which requires the same hardware as a full precision network.
However, restricting μ in the form of 2^n simplifies multiplication to shift operation to the right or left depending on the sign of the integer value n ∈ℤ, see <cit.>.

Our method provides a compromise between BC and TWN and trains weights with a single trainable scaling factor μ. Weights shift between ternary {-μ, 0, +μ} and binary {-μ, +μ}. This provides a single algorithm for 1 or 2 bits mixed precision.
 
 


 §.§ Regularization

Regularization technique is essential to prevent over-fitting problem and to obtain robust generalization for unseen data. Standard regularization functions, such as L_2 or L_1 encourage weights to be concentrated about the origin. However, in case of binary network it is more appropriate to have a regularization function to encourage the weights about μ×{-1,+1}, with a scaling factor μ >0 <cit.> such as ,

    R_1(w, μ) =  || w |-μ|,


A straightforward generalization for ternary quantization can be expressed as,

    R_2(w, μ) = ||| w |-μ/2| -  μ/2|.

Regularizer (<ref>) encourages weights about {-μ,+μ}, and (<ref>) about {-μ , 0, +μ}. The two functions are depicted in Figure <ref>. These regularization functions are only useful when the quantization depth is set before training starts. We propose a more flexible version to smoothly move between these two functions using a shape parameter β.







§ ADAPTIVE QUANTIZATION

Here we propose a generalized adaptive regularization function that switches between binary regularization of (<ref>) and ternary regularization of (<ref>) 

    min( | |w|+ μ|^p, | |w|- μ|^p,  tan(β)|w|^p ),

in which μ is a trainable scaling factor, p is the order coefficient denoting the type of regularization function, and β∈ (π/4 , π/2) controls the transition between (<ref>) and (<ref>). As a special case β→π/2 converges to the binary regularizer (<ref>)  and β→π/4 coincide with the ternary regularizer (<ref>), depicted in Figure <ref>. A large value of tan(β) repels estimated weights away from zero thus yielding binary quantization, and a small value of tan(β) encourages zero weights.  The shape parameter β controls the quantization depth. Quantization depth changes per layer; therefore we let β vary per layer. We recommend to regularize β about π/2 i.e. preferring binary quantization apriori by adding |(β)| to the objective function.

For a single filter  the regularization function can be expressed by a sum over its elements on row i and column j as,







    R(,μ, β) =    ∑_i=1^I∑_j=1^J min( | |w_ij|+ μ|^p, | |w_ij|- μ|^p , 
        tan(β)|w_ij|^p ) + γ |(β)|,


where γ controls the proportion of binary to ternary layers, i.e., large values of γ contributes to encouraging the layers to form binary values. 
In each layer, weights are pushed to binary or ternary values, depending on the trained value of the corresponding β. Here we only focus on such regularizer that is constructed using p=1, as the accuracy does not change significantly by varying the value of p. 

The introduced regularization function is added to the empirical loss function L(.). The objective function is optimized on set of parameter weights , set of scaling factors , and set of shape parameters   using back propagation  

    Ł(,,) =  L() +  ∑_l=1^L λ_l ∑_k=1^K  R(_kl, μ_kl,β_l),

where k indexes the channel in a convolution network, and l indexes the layer. One may use a different regularization constant λ_l for each layer to keep the impact of the regularization term balanced across layers, indeed different layers may involve different number of parameters. We set λ_l = λ#_l where λ is a constant, and #_l is the number of weights in layer l.



We propose to use the same threshold-based function of TWN <cit.>  (<ref>), but with a fixed threshold Δ_l per layer l. Note that <cit.> proposes a weight-dependant threshold. We enforce weights to only accumulate about { -μ, + μ} for large β_l. One may set Δ_l to have the same balanced weights in {-μ, 0, +μ} at initialization for all layers and let the weights evolve during training. Formally, if σ_l is the standard deviation of the initial Gaussian weights in layer l, we propose Δ_l = 0.2 ×σ_l. The probability that a single weight lies in the range [-Δ_l,Δ_l] is ≈ 0.16. All the weights falling in this range will be quantized as zeros after applying the threshold function. 

Weights are naturally pushed to binary or ternary values depending on β_l during training. Eventually, a threshold δ close to π 2≈ 1.57 defines the final quantization depth for each layer. 




    Final quantization depth of layer l :
      Binary   β_l   ≥δ,
    Ternary   β_l     <   δ







§ EXPERIMENTS

We run experiments on two common image classification tasks MNIST <cit.> and CIFAR10 <cit.> datasets. We compare our method, Smart Quantization (SQ), with BinaryConnect (BC) of <cit.>, Binary Weight Networks (BWN) of <cit.>, Ternary Weights Network (TWN) of <cit.> and also with a Full Precision network (FP). The quality of the compression is measured only in terms of memory, it is difficult to compare mixed precision models, with binary and ternary, in terms of consumed energy as their fair comparison requires specific hardware design. Let n_l be the quantization depth for the layer l and #_l the number of weights in layer l, therefore the  compression ratio is derived as, ∑_l=1^L #_l× 32/∑_l=1^L #_l× n_l.
The compression ratio for a binary network is 32, for a ternary network 16, and our approach falls in between.

Our SQ network generalizes binary and ternary regularization in a single regularization function. We present how to control the proportion of binary and ternary layers using γ in (<ref>). Figure <ref> clarifies the effect of γ on the weight distribution. When γ is large, β is encouraged towards π 2 which corresponds to binary quantization. Thus, weights are pushed about {-μ,+μ} and 0 is removed from the trained values, see Figure <ref>. On the contrary, when γ is small, β tends to π 4 and the weights started including 0 in their values, see Figure <ref>. 
In our experiment, the parameters ,  and  are trainable; p, δ_l, Δ_l, λ_l, and γ are tuning parameters.






 §.§ MNIST

MNIST is an image classification benchmark dataset with  28 × 28 gray-scale images representing digits ranging from 0 to 9. The dataset is split into 60k training images and 10k testing images. We used the LeNet-5 <cit.> architecture consisting of 5 layers, 2 convolution followed by maxpooling, stacked with two fully connected layers and a softmax layer at the end. We train the network for 60 epochs using Adam optimizer. We used the initial learning rate of 0.01, but divided by 10 in epoch 15 and 30 to stabilize training. The batch size is set to 64 with L_2 weight decay constant  10^-4 only for BC, BWC and TWN. The full precision LeNet-5 is trained with no regularization as it provided a superior accuracy. SQ is trained with λ= 10^-1 and γ = 10^-2 and the effective regularization constant is divided by the number of weights in each layer to compensate for the layer size. Validation accuracy for each method is reported in Table <ref>, as well as the quantization depth, and the overall compression ratio. We observe that SQ network quantized the first two convolutional layers in 1 bit, and the last fully-connected layers in 2 bits. The accuracy improvement and the compression ratio is marginal for simple task and simple architectures. The effect of smart training becomes more visible for more complex tasks with more layers.  







 §.§ CIFAR10


CIFAR10 is an image classification benchmark that contains 32 × 32 RGB images from ten classes. The dataset is split into 50k training images and 10k testing images. All images are normalized using mean = (0.4914, 0.4822, 0.4465) and std = (0.247,0.243,0.261). For the training session, we pad the sides of the images with 4 pixels, then sample a crop of size  32× 32, and flip horizontally at random as our augmentation process.







We use two VGG-like architectures, i) VGG-7 architecture defined in <cit.> in which we apply batch normalization after each layer and use ReLU activations, ii) a standard VGG-16 architecture. We did not quantize the first and the last layers in VGG-16 as the accuracy dropped significantly for all methods.

We train the network for 150 epochs, using Adam optimizer with the initial learning rate 0.001 divided by 10 at epochs 40 and 80. The batch size is set to 64 with L_2 weight decay constant 10^-4, moreover λ=0.1, γ= 10^-3 for SQ. Validation accuracy for each method is reported in Table <ref>. SQ beats pure 2 bits network TWN,  even in terms of accuracy. It recommends  three 1 bit layers for VGG-7 and seven 1 bit layers for VGG-16. The compression ratio is significantly higher than a ternary network. The weight distribution of each layers are depicted in Figure <ref> for the VGG-7 architecture. Weights are pushed to {-μ,+μ} or {-μ,0,+μ} depending on the shape parameter β.




§ CONCLUSIONS


We proposed Smart Quantization (SQ), a training method to build a 1 and 2 bits mixed quantized DNN. 
Depth optimization requires training network multiple times which is costly, especially if the network is complex. However, our proposed method successfully combines quantization with different depths, while training the network only once. We focused on layer-wise quantization, since it is more suitable for mixed-precision inference implementation. However, subnetwork, block, filter, or weight mixed quantization is feasible using a similar algorithm. 
 
 SQ makes manual tuning of quantization depth unnecessary. It allows to improve the memory consumption, by automatically quantizing some layers with smaller precision. In some cases, this method even outperforms pure ternary networks in terms of accuracy due to a formal regularization function that shapes trained weights towards mixed-precision.  
It is well-known that some layers are more resilient to aggressive quantization. Our proposed methodology offers a network similar to pure ternary but gives an insight about which layers can be simplified further by adapting to binary quantization. Scaling the method for complex tasks such as ImageNet and with deeper architectures is challenging and requires further research. A similar methodology can be applied to quantize neural network models designed for other tasks related to speech and text.





ieee_fullname



