{'fraction_non_alphanumeric': 0.03323386795971652, 'fraction_numerical': 0.012607236105930623, 'mean_word_length': 4.456043956043956, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, '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}}
PR Product: A Substitute for Inner Product in Neural Networks

In this paper, we analyze the inner product of weight vector w and data vector x in neural networks from the perspective of vector orthogonal decomposition and prove that the direction gradient of w decreases with the angle between them close to 0 or {\pi}. We propose the Projection and Rejection Product (PR Product) to make the direction gradient of w independent of the angle and consistently larger than the one in standard inner product while keeping the forward propagation identical. As a reliable substitute for standard inner product, the PR Product can be applied into many existing deep learning modules, so we develop the PR Product version of fully connected layer, convolutional layer and LSTM layer. In static image classification, the experiments on CIFAR10 and CIFAR100 datasets demonstrate that the PR Product can robustly enhance the ability of various state-of-the-art classification networks. On the task of image captioning, even without any bells and whistles, our PR Product version of captioning model can compete or outperform the state-of-the-art models on MS COCO dataset. Code has been made available at:https://github.com/wzn0828/PR_Product.


Introduction
Models based on neural networks, especially deep convolutional neural networks (CNN) and recurrent neural networks (RNN), have achieved state-of-the-art results in various computer vision tasks [11,10,1]. Most of the optimization algorithms for these models rely on gradientbased learning, so it is necessary to analyze the gradient of inner product between weight vector w ∈ R d and data vector x ∈ R d , a basic operation in neural networks. Denoted by P (w, x) = w T x the inner product, the gradient † The authors are with College of Electronic and Information Engineering, the Shenzhen Key Laboratory of Advanced Machine Learning and Applications, the Guangdong Key Laboratory of Intelligent Information Processing, Shenzhen University. * Corresponding author is with the College of Mathematics and Statistics, Shenzhen University. of P (w, x) w.r.t. w is exactly the data vector x which can be orthogonally decomposed into the vector projection P x on w and the vector rejection R x from w, as shown in Figure 1 (a). The vector projection P x is parallel to the weight vector w and will update the length of w in next training iteration, called the length gradient. While the vector rejection R x is orthogonal to w, it will change the direction of w, called the direction gradient. Driven by the orthogonal decomposition of the gradient w.r.t. w, a question arises: Which is the key factor for optimization, length gradient or direction gradient? To answer this question, we optimize three 5-layer fully connected neural networks on Fashion-MNIST [36] with different variants of inner product: standard inner product, a variant without length gradient and a variant without direction gradient. The top-1 accuracy is 88.42%, 88.32% and 38.59%, respectively. From these comparative experiments we can observe that the direction gradient is the key factor for optimization and is far more critical than the length gradient, which might be unsurprising. However, the direction gradient would be very small when w and x are nearly parallel, which would hamper the update of the direction of weight vector w.
On the other hand, in Euclidean space, the geometric definition of inner product is the product of the Euclidean lengths of the two vectors and the cosine of the angle between them. That is P (w, x) = w T x = w 2 x 2 cos θ, where we denote by * 2 the Euclidean length of vector * and by θ the angle between w and x with the range of [0, 2π). From this formulation, we can see that the θ is strongly connected with the direction of weight vector w. The gradient of P w.r.t. θ is ∂P/∂θ = − w 2 x 2 sin θ, which becomes small with θ close to 0 or π and thus hinders the optimization. Several recent investigations of backpropagation [4,43] focus on modifying the gradient of activation function. However, few researches propose variants of backpropagation for the inner product function.
In this paper, we propose the Projection and Rejection Product(abbreviated as PR Product) which changes the backpropagation of standard inner product to eliminate the dependence of the direction gradient of w and the gradient w.r.t. θ on the value of θ. We firstly prove that the standard inner product of w and x only contains the information of vector projection P x , which is the main cause of the above dependence. While our proposed PR Product involves the information of both the vector projection P x and the vector rejection R x through rewriting the standard inner product into a different form and suitable components of that form are held fixed during backward pass. We further analyze the gradients of PR Product w.r.t. θ and w. For θ, the absolute value of gradient changes from w 2 x 2 |sin θ| to w 2 x 2 . For w, the length of direction gradient changes from x 2 |sin θ| to x 2 , as shown in Figure 1.
There are several advantages of using PR Product:(a)The PR Product gets a different backward pass while the forward pass remains exactly the same as the standard inner product; (b) Compared with the behavior of standard inner product, PR increases the proportion of the direction gradient which is the key factor for optimization; (c) As the PR Product maintains the linear property, it can be a reliable substitute for inner product operation in the fully connected layer, convolutional layer and recurrent layer. By reliable, we mean it does not introduce any additional parameters and matches with the original configurations such as activation function, batch normalization and dropout operation.
We showcase the effectiveness of PR Product on image classification and image captioning tasks. For both tasks, we replace all the fully connected layers, convolutional layers and recurrent layers of the backbone models with their PR Product version. Experiments on image classification demonstrate that the PR Product can typically improve the accuracy of the state-of-the-art classification models. Moreover, our analysis on image captioning confirms that the PR Product definitely change the dynamics of neural networks. Without any tricks of improving the performance, like scene graph and ensemble strategy, our PR Product version of captioning model achieves results on par with the state-ofthe-art models.
In summary, the main contributions of this paper are: • We propose the PR Product, a reliable substitute for the standard inner product of weight vector w and data vector x in neural networks, which changes the backpropagation while keeping the forward propagation identical; • We develop the PR-FC, PR-CNN and PR-LSTM, which applies the PR Product into the fully connected layer, convolutional layer and LSTM layer respectively; • Our experiments on image classification and image captioning suggest that the PR Product is generally effective and can become a basic operation of neural networks.

Related Work
Variants of Backpropagation. Several recent investigations have considered variants of standard backpropagation. In particular, [22] presents a surprisingly simple backpropagation mechanism that assigns blame by multiplying errors signals with random weights, instead of the synaptic weights on each neuron, and further downstream. [2] exhaustively considers many Hebbian learning algorithms. The straight-through estimator proposed in [4] heuristically copies the gradient with respect to the stochastic output directly as an estimator of the gradient with respect to the sigmoid argument. [43] proposes Linear Backprop that backpropagates error terms only linearly. Different from these methods, our proposed PR Product changes the gradient of inner product function during backpropagation while maintaining the identical forward propagation. Image Classification. Deep convolutional neural networks [18,32,11,12,45,37,13] have become the dominant machine learning approaches for image classification. To train very deep networks, shortcut connections have become an essential part of modern networks. For example, Highway Networks [33,34] present shortcut connections with gating functions, while variants of ResNet [11,12,45,37] use identity shortcut connections. DenseNet [13], a more recent network with several parallel shortcut connections, connects each layer to every other layer in a feed-forward fashion. Image Captioning. In the early stage of vision to language field, template-based methods [7,20] generate the caption templates whose slots are filled in by the outputs of object detection, attribute classification and scene recognition, which results in captions that sound unnatural. Recently, inspired by the advances in the NLP field, models based encoder-decoder architecture [17,16,35,14] have achieved striking advances. These approaches typically use a pretrained CNN model as the image encoder, combined with an RNN decoder trained to predict the probability distribution over a set of possible words. To better incorporate the image information into the language processing, visual attention for image captioning was first introduced by [38] which allows the decoder to automatically focus on the image subregions that are important for the current time step. Because of remarkable improvement of performance, many extensions of visual attention mechanism [44,5,40,9,27,1] have been proposed to push the limits of this framework for caption generation tasks. Except for those extensions to visual attention mechanism, several attempts [31,26] have been made to adapt reinforcement learning to address the discrepancy between the training and the testing objectives for image captioning. More recently, some methods [41,15,25,39] exploit scene graph to incorporate visual relationship knowledge into captioning models for better descriptive abilities.

The Projection and Rejection Product
In this section, we begin by shortly revisiting the standard inner product of weight vector w and data vector x. Then we formally propose the Projection and Rejection Product (PR Product) which involves the information of both vector projection of x onto w and vector rejection of x from w. Moreover, we analyze the gradient of PR Product. Finally, we develop the PR Product version of fully connected layer, convolutional layer and LSTM layer. In the following, for the simplicity of derivation, we only consider a single data vector x ∈ R d and a single weight vector w ∈ R d except for the last subsection.

Revisit the Inner Product in Neural Networks
In Euclidean space, the inner product P of the two Euclidean vectors w and x is defined by: where * 2 is the Euclidean length of vector * , and θ is the angle between w and x with the range of [0, 2π). From this formulation, we can observe that the angle θ explicitly affects the state of neural networks. The gradient of P w.r.t. θ. Neither the weight vector w nor the data vector x is the function of θ, so it is easy to get: The gradient of P w.r.t. w. From Equation (1) and Figure  1 (a), it is easy to obtain the gradient function of P w.r.t. w: Here, R x is the direction gradient of w. From Figure 1 (a) and Equation (2), we can see that either the value of the gradient of P w.r.t. θ or the length of R x is close to 0 with θ close to 0 or π, which would hamper the optimization of neural networks.
From Figure 1 (a),we can easily get the length of P x : And the length of R x is: So equation (1) can be reformulated as: where sign(*) denotes the sign of *. We can observe that this formulation only contains the information of vector projection of x on w, P x . As shown in Figure 1, the vector projection P x changes very little when θ is near 0 or π, which may be a block to the optimization of neural networks. Although the length of the rejection vector R x is small when θ is close to 0 or π, it varies greatly and thus is able to support the optimization of neural networks. That is our basic motivation for the proposed PR Product.

The PR Product
In order to take advantage of the vector rejection, the simplest way is to replace the P x 2 in Equation (6) with P x 2 + R x 2 . But the trends of P x 2 and R x 2 with θ are inconsistent, so we employ x 2 − R x 2 to involve the information of vector rejection. In addition, we utilize two coefficients to maintain the linear property, which are held fixed during the backward pass. To be more detailed, we derive the PR Product as follows: For clarity, we denote by P R the proposed product function. Note that the * denotes detaching * from neural networks. By detaching, we mean * is considered as a constant rather than a variable during backward propagation. Compared with the standard inner product formulation (Equation (6) or (1)), this formulation involves not only the information of vector projection P x but also the one of vector rejection R x without any additional parameters. We call this formulation the Projection and Rejection Product or PR Product for brevity.
Although the PR Product does not change the outcome during forward pass, compared with the standard inner product, it changes the gradients during backward pass. In the following, we theoretically derive the gradient of P R w.r.t. θ and w during backpropagation.
The gradient of P R w.r.t. θ. We just need to calculate the gradients of trigonometric functions except for the detached ones in Equation (7). When θ is in the range of [0, π), the gradient of P R w.r.t. θ is: When θ is in the range of [π, 2π), the gradient of P R w.r.t. θ is: We use the following unified form to express the above two cases: Compared with the standard inner product (Equation (2)), the PR Product changes the gradient w.r.t. θ from a smoothing function to a hard one. One advantage of this is the gradient w.r.t. θ does not decrease as θ gets close to 0 or π, providing continuous power for the optimization of neural networks.
The gradient of P R w.r.t. w. Above we discussed the gradient w.r.t. θ, an implicit variable in neural networks. In this part, we explicitly take a look at the differences between the gradients of the standard inner product and our proposed PR Product w.r.t. w .
For the PR Product, we derive the gradient of P R w.r.t.
w from Equation (7) and Equation (10) as follows : Where M w is the projection matrix that projects onto the weight vector w, which means M w x = P x , and E rx is the unit vector along the vector rejection R x . Similar to Equation (3), the P x is the length gradient part and the x 2 E rx is the direction gradient part. For the length gradient, the cases in P and P R are identical. For the direction gradient part, however, the one in P R is consistently larger than the one in P , except for the almost impossible cases when θ is equal to π/2 or 3π/2. So P R increases the proportion of the direction gradient. In addition, the length of direction gradient in P R is independent of the value of θ. Figure 1 shows the comparison of the gradients of the two formulations w.r.t. w.

PR-X
The PR Product is a reliable substitute for the standard inner product operation, so it can be applied into many existing deep learning modules, such as fully connected layer(FC), convolutional layer(CNN) and LSTM layer. We denote the module X with PR Product by PR-X. In this section, we show the implementation of PR-FC, PR-CNN and PR-LSTM. PR-FC. To get PR-FC, we just replace the inner product of the data vector x and each weight vector in the weight matrix with the PR Product. Suppose the weight matrix W contains a set of n column vectors, W = (w 1 , w 2 , ..., w n ), so the output vector of PR-FC can be calculated as follows: = (P R(w 1 , x), P R(w 2 , x), ..., P R(w n , x)) + b tensor in the sliding window into vectors in Euclidean space, and then use the PR Product to calculate the output. Suppose the size of the convolution kernel w is (k 1 , k 2 , C in ), so the output at position (i, j) is: where f latten(w) and f latten( represents the data tensor in the sliding window corresponding to output position (i,j), and b represents an additive bias if any. PR-LSTM. To get the PR Product version of LSTM, just replace all the perceptrons in each gate function with the PR-FC. For each element in input sequence, each layer computes the following function: where σ is the sigmoid function, and * is the Hadamard product.
In the following, we conduct experiments on image classification to validate the effectiveness of PR-CNN. And then we show the effectiveness of PR-FC and PR-LSTM on image captioning task.

Dataset and Settings
We conduct our image classification experiments on the CIFAR dataset [19], which consists of 50k and 10k images of 32 × 32 pixels for the training and test sets respectively. The images are labeled with 10 and 100 categories, namely CIFAR10 and CIFAR100 datasets. We present experiments trained on the training set and evaluated on the test set. We follow the simple data augmentation in [21] for training: 4 pixels are padded on each side and a 32 × 32 crop is randomly sampled from the padded image or its horizontal flip. For testing, we only evaluate the single view of the original 32 × 32 image. Note that our focus is on the effectiveness of our proposed PR Product, not on pushing the state-of-the-art results, so we do not use any more data augmentation and training tricks to improve accuracy.

Results and Analysis
For fair comparison, not only are the PR-X models trained from scratch but also the corresponding backbone models, so our results may be slightly different from the ones presented in the original papers due to some hyperparameters like random number seeds. The strategies and hyper-parameters used to train the respective backbone models, such as the optimization solver, learning rate schedule, parameter initialization method, random seed for initialization, batch size and weight decay, are adopted to train the corresponding PR-X models. The results are shown in Table 1 and some training curves are shown in the supplementary material, from which we can see that the PR-X can typically improve the corresponding backbone models on both CIFAR10 and CIFAR100. On average, it reduces the top-1 error by 0.27% on CIFAR10 and 0.16% on CIFAR100. It is worth emphasizing that the PR-X models don't introduce any additional parameters and keep the same hyper-parameters as the corresponding backbone models.

Captioning Model
We utilize the widely used encoder-decoder framework [1,27] as our backbone model for image captioning. Encoder. We use the Bottom-Up model proposed in [1] to generate the regional representations and the global representation of a given image I . The Bottom-Up model employs Faster R-CNN [29] in conjunction with the ResNet-101 [11] to generate a variably-sized set of k representations, A = {a 1 , ..., a k }, a i ∈ R 2048 , such that each representation encodes a salient region of the image. We use the global average pooled image representation a g = activation function to transform the representation vectors into new vectors with dimension d: where W a and W g are the weight parameters. The transformed V = {v 1 , ..., v k } is our defined regional image representations and v g is our defined global image representation.
Decoder. For decoding image representations V and v g to sentence description, as shown in Figure 2, we utilize an visual attention model with two PR-LSTM layers according to recent methods [1,28,41], which are characterized as Attention PR-LSTM and Language PR-LSTM respectively. We initialize the hidden state and memory cell of each PR-LSTM as zero. Given the output h 1 t of the Attention PR-LSTM, we generate the attended regional image representationv t through the attention model, which is broadly adopted in recent previous work [5,27,1]. Here, we use the PR Product version of visual attention model expressed as follows: where W v , W h1 and W z are learned parameters, f 1 and f 2 are the outputs of the first layer and the second layer in the attention model respectively. α t is the attention weight over k regional image representations, andv t is the attended image representation at time step t.

Dataset and Settings
Dataset. We evaluate our proposed method on the MS COCO dataset [23]. MS COCO dataset contains 123287  images labeled with at least 5 captions. There are 82783 training images and 40504 validation images, and it provides 40775 images as the test set for online evaluation as well. For offline evaluation, we use a set of 5000 images for validation, a set of 5000 images for test and the remains for training, as given in [16]. We truncate captions longer than 16 words and then build a vocabulary of words that occur at least 5 times in the training set, resulting in 9487 words. Implementation Details. In the captioning model, we set the number of hidden units in each LSTM or PR-LSTM to 512, the embedding dimension of a word to 512, and the embedding dimension of image representation to 512. All of our models are trained according to the following recipe. We train all models under the crossentropy loss using ADAM optimizer with an initial learning rate of 5 × 10 −4 and a momentum parameter of 0.9. We anneal the learning rate using cosine decay schedule and increase the probability of feeding back a sample of the word posterior by 0.05 every 5 epochs until we reach a feedback probability 0.25 [3]. We then run REINFORCE training to optimize the CIDEr metric using ADAM with a learning rate 5 × 10 −5 with cosine decay schedule and a momentum parameter of 0.9. During CIDEr optimization mode and testing mode, we use a beam size of 5. Note that in all our model variants, the untransformed image representations A and a g from the Encoder are fixed and not fine-tuned. As our focus is on the effectiveness of our proposed PR Product, so we just exploit the widely used backbone model and settings, without any additional tricks of improving the performance, like scene graph and ensemble strategy.

Performance Comparison and Experimental Analysis
The effectiveness of PR Product. To test the effectiveness of PR Product, we first compare the performance of models using the following different substitutes for inner product on Karpathy's split of MS COCO dataset: • P Product: This is just the standard inner product. In Euclidean geometry, it is also called projection product, so we abbreviate it as P Product.
• R Product: Contrary to P Product, R Product only involves the information of vector rejection of x from w. To keep the same range and sign as P Product, we formulate the R Product as follows: • PR Product: This is the proposed PR Product. Evidently, the PR Product is the combination of the P Product and R Product with the relationship as follows: For fair comparison, results are reported for models trained with cross-entropy loss and models optimized for To better understand how the PR Product affects neural networks, we plot the minimum of | sin θ| to investigate the dynamics of neural networks to some extent. Figure 3 shows the statistic of the hidden-hidden transfer part in the Attention LSTM, and plots for more layers can be found in the supplementary material. For most of the layers, the minimum of | sin θ| in PR Product version is larger than the one in P Product, which means the weight vector and data vector in PR Product are more orthogonal. We argue this is the reason for PR Product to take effect.
Comparison with State-of-the-Art Methods. To further verify the effectiveness of our proposed method, we also compare the PR Product version of our captioning model with some state-of-the-art methods on Karpathy's split of MS COCO dataset. Results are reported in Table 3, of which the top part is for cross-entropy loss and the bottom part is for CIDEr optimization.
Among those methods, SCN-LSTM [8] and SCST:Att2all [31] use the ensemble strategy. GCN-LSTM [41], CAVP [25] and SGAE [39] exploit information of visual scene graphs. Even though we do not use any of the above means of improving performance, our PR Product version of captioning model achieves the best performance in most of the metrics, regardless of crossentropy training or CIDEr optimization. In addition, we also report our results on the official MS COCO evaluation server in Table 4. As the scene graph models can greatly improve the performance, for fair comparison, we only report the results of methods without scene graph models. It is noteworthy that we just use the same model as reported in Table 3, without retraining on the whole training and validation images of MS COCO dataset. We can see that our single model achieves competitive performance compared with the state-of-the-art models, even though some models exploit ensemble strategy.

Conclusion
In this paper, we propose a reliable substitute for the inner product of weight vector w and data vector x, the PR Product, which involves the information of both the vector projection P x and the vector rejection R x . The length of the direction gradient of PR Product w.r.t. w is consistently larger than the one in standard inner product. In particular, we show the PR Product version of the fully connected layer, convolutional layer and LSTM layer. Applying these PR Product version modules to image classification and image captioning, the results demonstrate the robust effectiveness of our proposed PR Product. As the basic operation in neural networks, we will apply the PR Product to other tasks like object detection. Figures 4-7 show the training curves of some classification models on CIFAR10 used in the paper, from which we can see that the models of PR Product version get consistent lower error rates than the models of standard inner product version.     B. The Minimum of | sin θ| | sin θ| | sin θ|

A. Training Curves on CIFAR10
We plot the minimum of | sin θ| in some layers of our captioning model, as shown in Figures 8-16. From these plots, we can observe that the minimum of | sin θ| in PR Product version is larger than the one in P Product version for most of the layers, which means the weight vector and data vector in PR Product are more orthogonal. We argue this is the reason for PR Product to take effect.

C. Examples of Image Captioning
To intuitively illustrate the advantage of the PR Product, we show some examples of image captioning in Figure 17. The images are sampled from Karpathy's test split of MS COCO dataset. All the three models (P version, R version, and PR version) are trained with cross-entropy loss and then fine-tuned for CIDEr optimization. The results show that PR product makes contribution to the descriptiveness of the sentences and prove that the PR Product is effective.