{'fraction_non_alphanumeric': 0.037118729518527856, 'fraction_numerical': 0.01518779934459289, 'mean_word_length': 4.6393034825870645, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 1, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Adaptive Binary-Ternary Quantization

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 [3]. More specifically, in computer vision DNN have led to a series of breakthrough for image classification [6], [16], [17], and object detection [14], [11], [15]. 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 [1], [4], [13], [19], [9], [2] represent weights with 1 bit precision and ternary quantization [10], [8], [20] 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) [1] and Ternary Weight Network (TWN) [8] toward automatic 1 or 2 bits mixed-precision using a single training algorithm.
In BC [1], 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, The derivative of the sign function is zero on R \ {0}. The sign function has zero gradient which freezes weight up-dates during back-propagation. To bypass this problem, BC [1] uses a clipped straight-through estimator where L is the loss function and 1 A (.) is the indicator function on the set A. In other words (2)  where µ = E |W| ∈ R. DoReFa-Net [19] generalizes the latter work and approximates the full precision weights with more than one bit, while ABCNet [9] approximates weights with a linear combination of multiple binary weight bases.

Ternary weight networks
Ternary Weight Network (TWN) [8] 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 [8] finds the closest ternary weights matrix W t to its corresponding real value weight matrix W using (3) The ternary weight W t is achieved by applying a symmetric threshold ∆ One may adopt a weight-dependant threshold ∆ and a scaling factor µ that approximately solves (3). 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 X as, where denotes the convolution.
Trained Ternary Quantization (TTQ) [20] 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 ∈ Z, see [18].
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 overfitting 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 [12] such as , A straightforward generalization for ternary quantization can be expressed as, Regularizer (6) encourages weights about {−µ, +µ}, and (7) about {−µ, 0, +µ}. The two functions are depicted in Figure 1. 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 (6) and ternary regularization of (7) 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 (6) and (7). As a special case β → π 2 converges to the binary regularizer (6) and β → π 4 coincide with the ternary regularizer (7), depicted in Figure 2. 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 | cot(β)| to the objective function.
For a single filter W the regularization function can be expressed by a sum over its elements on row i and column j as, 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 W, set of scaling factors µ, and set of shape parameters β using back propagation 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 = λ #W l where λ is a constant, and #W l is the number of weights in layer l.
We propose to use the same threshold-based function of TWN [8] (4), but with a fixed threshold ∆ l per layer l. Note that [8] 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.

Experiments
We run experiments on two common image classification tasks MNIST [7] and CIFAR10 [5] datasets. We compare our method, Smart Quantization (SQ), with BinaryConnect (BC) of [1], Binary Weight Networks (BWN) of [13], Ternary Weights Network (TWN) of [8] 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 #W l the number of weights in layer l, therefore the compression ratio is derived as, 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 (8). Figure 3 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 3a. On the contrary, when γ is small, β tends to π 4 and the weights started including 0 in their values, see Figure 3b. In our experiment, the parameters W, µ 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 [7] 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 1, 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.
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 [8] 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 2. 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 Figure 4: Layer-wise weights distribution in VGG-7 for SQ. The weights are pushed to binary when the shape parameter β is close to π 2 ≈ 1.57.
is significantly higher than a ternary network. The weight distribution of each layers are depicted in Figure 4 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 mixedprecision. 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.