# Constrained-size Tensorflow Models for YouTube-8M Video Understanding Challenge

This paper presents our 10th place solution to the second YouTube-8M video understanding competition which challenges participates to build a constrained-size model to classify millions of YouTube videos into thousands of classes. Our final model consists of four single models aggregated into one tensorflow graph. For each single model, we use the same network architecture as in the winning solution of the first YouTube-8M video understanding competition, namely Gated NetVLAD. We train the single models separately in tensorflow's default float32 precision, then replace weights with float16 precision and ensemble them in the evaluation and inference stages., achieving 48.5 88.324 https://github.com/boliu61/youtube-8m

## Authors

##### This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.

## 1 Introduction

Enormous amount of video content is generated all over the world every day. As an important research topic in computer vision, video analysis has many applications such as recommendation, search, and ranking. Recently, video classification problem gained interest with broad range of applications such as emotion recognition , human activity understanding , and event detection .

YouTube-8M dataset  released by Google AI consists of over 6 million YouTube videos of 2.6 billion audio and visual features with 3,700+ of associated visual entities on average of 3.0 labels per video. Each video was decoded at 1 frame-per-second up to the first 360 seconds, after which features were extracted via pre-trained model. PCA and quantization were further applied to reduce dimensions and data size. Visual features of 1024 dimensions and audio features of 128 dimensions were extracted on each frame as input for downstream classifiers.

Following the first YouTube8M Kaggle competition, the second one is focused on developing compact models no greater than 1 GB uncompressed so that it can be applicable on user’s personal mobile phones for personalized and privacy-preserving computation. Challenges in such competition include modeling correlations between labels, handling multiple sequential frame-level features, and efficient model compression.

In the competition, Global Average Precision (GAP) at 20 is used as metric. For each video, the model should predict 20 most confident labels with associated confidence (probability). The list of

tuples is sorted by confidence levels in descending order. GAP is then computed as:

 GAP=N∑i=1p(i)Δr(i) (1)

where is the precision, and is the recall.

Common approach for video analysis typically extract features from consecutive features followed by feature aggregation. Frame-level feature extraction can be achieved by applying pre-trained Convolutional Neural Networks (CNN)

[6, 7, 8, 9]. Common methods for temporal frame feature aggregation include Bag-of-visual-words [10, 11]

, Fisher Vectors

, Convolutional Neural Networks (CNN) 

, Gated Recurrent Unit (GRU)



, Long Short-Term Memory (LSTM)

, and Generalized Vector of Locally Aggregated Descriptors (NetVLAD) .

It is well-known that neural networks are memory intensive and deploying such models on mobile devices is difficult for its limited hardware resources. Several approaches were proposed to tackle such difficulty. A straight forward way is to apply tensor decomposition techniques

[17, 18, 19] to a pretrained CNN model . Network Pruning removes low-weight connections on pretrained models , or gradually trains binary masks and weights until target sparsity is reached . Network quantization compresses network by reducing number of bits required to represent each weight via weight sharing , or vector quantization . Another way to get better performance for limited-size model is to use knowledge distillation [25, 26]. The idea behind it is to train student network (small size) to imitate the soft output of a larger teacher network or ensembles of networks.

In Google cloud & YouTube-8M video understanding challenge Kaggle competition, top participates [1, 27, 28, 29, 30] trained models such as Gated NetVLAD, GRU, and LSTM with Attention. To leverage the predictability of single models, they averaged checkpoints at different training steps and ensembled predicted probability scores by weighted average, bagging, or boosting.

Our contribution in this paper is threefold: First, we explore size and performance of Gated NetVLAD under different sets of hyper-parameters (cluster size and hidden size). Second, we develop ensemble approach of multiple models in one tensorflow graph which avoids in-place change of graph. Third, we cast trained weights tensors from float32 to float16 data type in evaluation and inference stage which reduces approximately half the model size without sacrificing performance.

The rest of the paper is organized as follows. Section 2 presents our model architecture with compression and ensemble approaches. Section 3 reports experimental results, followed by conclusions in Section 4.

## 2 Approach

In this section, we first introduce Gated NetVLAD model architecture, then describe model compression approaches we have tried, followed by ensemble approaches we developed.

### 2.1 Frame Level Models

Our architecture for video classification is illustrated in Fig. 1 Figure 1: Overview of our model architecture. FC denotes Fully Connected layer. MoE denotes Mixture of Experts.

The NetVLAD  is a trainable generalized VLAD layer that captures information about the statistics of local descriptors over the image, i.e., the sum of residuals for each visual word. More specifically, let th descriptor (video or audio feature) of a video be , which can be assign to one of clusters with centroid for . The NetVLAD can be written as summation of residuals with soft assignment

 V(j,k)=N∑i=1ewTkxi+bk∑k′ewTk′xi+bk′(xi(j)−ck(j)) (2)

where , and are sets of trainable parameters for each cluster . Number of clusters (referred as cluster size) is a hyper-parameter we varies across different models.

#### 2.1.2 Fully Connected layer

Our FC layer consists of two layers. First layer get input of concatenated video and audio VLAD layer, multiplied by weight matrix resulting in hidden size

, followed by batch normalization and ReLU activation. Second layer takes output of first layer as input, multiplied by weight matrix of shape

and added by a bias term.

#### 2.1.3 Context Gating

Context Gating (CG)  is a learnable non-linear unit aiming to model interdependencies among network activations by gating. Concretely, CG transform input vector to output vector of same dimension via

 Y=σ(WX+b)∘X (3)

where and are trainable parameters. is element-wise sigmoid activation and is the element-wise multiplication. CG is known for being able to capture dependencies among features.

#### 2.1.4 Mixture of Experts

Mixture of Experts (MoE)  consists of two parts, gating and experts. The final predictions are sum of products of last layers from gating and experts. We use 5 mixtures of one hidden layer experts. Gate activations are multiplied to each expert for probability prediction. MoE is further followed by CG modeling dependencies among video vocabulary labels.

#### 2.1.5 Training

We use two local GPUs, Nvidia 1080Ti and Nvidia 1060, and two Google Cloud Platform accounts with Tesla K80 GPUs to train single models. The training time is two to three days per model for 200k steps with batch size between 80 and 160.

The YouTube-8M Dataset is partitioned into three parts: Train, Validate and Test. Both Train and Validate data come with labels so they are effectively exchangeable. In order to maximize the number of training samples as well as to speed up the evaluation step, we randomly chose 60 out of the 3844 validate files as our validate set, and combine the other validate files with the official train dataset as our training set. We observe constant delta between our validate set and public leaderboard.

### 2.2 Compression

#### 2.2.1 Float16 Compression

Of the compression methods we have attempted, this is the only one that worked. The idea is to train all the models in the default float32 precision to achieve maximum score, then at evaluation/inference stage, cast all the inference weight tensors to float16 precision to cut model size in half while preserving prediction accuracy.

In actual implementation, we only cast 4 out of the 32 weight tensors in our model architecture. This is because the largest 4 tensors (

‘tower/experts/weights’,
‘tower/gates/weights’,
‘tower/gating_prob_weights’,
‘tower/hidden1_weights/hidden1_weights’


) make up about 98% of total model size. Modifying the other 28 small weight tensors does not worth the effort in our opinion, since float32 is the default data type in many tensorflow modules and functions, and we had to extend tensorflow’s core.Dense class and layers.fully_connected function to support float16 precision in order to cast those 4 tensors.

The average compression rate is 48.5% across models, as shown in Table 1. Compared to the original float32 models, the float16 compression version perform equally well, with GAPs differing less than 0.0001, which is the level of randomness between different evaluation runs for the same float32 model.

We tried method introduced by  as the tensorflow implementation is available on tensorflow’s github repo. For every layer chosen to be pruned, the authors added a binary mask variable of the same shape to determine which elements participate in forward execution of the graph. They introduced gradual pruning algorithm updating binary weight masks along with weight in network training. They claimed to achieve high compression rate without losing significant accuracy.

However, we found two main difficulties of the method in our experiments:

1. The sparsity is not identical to compression rate. In the article, sparsity was referred as the ratio between number of non-zero elements of the pruned network and the original network, while after compression the sparse tensor has indices that takes additional storage. Although the authors considered bit-mask and CSR(C) sparse matrix representation, there are still two problems we could not solve easily: First, Tensorflow boolean variable takes one byte (not one bit) thus in real implementation the compression rate will be much lower. Second, for large tensors with huge indices range, row and column indices should have each element of type 32 or 64 bit integers, which takes a huge storage.

For example, if we use float32 to store a tensor of 1024x100000 and set sparsity as . To make use of SparseTensor object in Tensorflow, for each non-zero element, we need to associate it with two 32 bit integers (row and column index). This results in only compression rate though sparsity is set to be . Furthermore, it losses of non-zero elements and sacrifices accuracy with only compression rate. This is not as appealing as float16 compression approach.

2. At the time of competition deadline, the github repo 111
aa15692e54390cf3967d51bc60acf5f783df9c08/tensorflow/contrib/model_pruning

for model pruning only contained the training part that associates tensor to be pruned with binary masks. The sparse tensor representation and bit mask were not implemented at the moment. We implemented it ourselves and found the compression rate not satisfiable.

After some trials and errors and comparison with float16 compression procedure, we decided not to pursue pruning for model compression.

#### 2.2.3 Quantization

Quantization  can achieve compression rate by representing element in tensor as 8 bits unsigned integers rather than 32 bits float value. Tensorflow provides useful tools to quantize a pretrained graph. However, we found the output of graph to be frozen graph of pb format. We were able to convert meta, index, and checkpoint files to pb file, but not vice versa. Yet the competition requires that the submitted model must be loadable as a TensorFlow MetaGraph. We did not overcome this technical difficulty and went with our float16 compression method for its easy and elegant usage.

### 2.3 Ensemble

#### 2.3.1 Checkpoint Average

For each single model, we first evaluate validation set using single checkpoints at some interval (say, every 10k steps) in order to know the approximate range of steps corresponding to higher scores for a particular model. Then we select a few ranges with varying starting and ending steps, and average all the checkpoints in that range. Finally we evaluate using these average points and pick the best one to represent this single model in the ensemble. On average, the averaged checkpoint gives a 0.0039 GAP boost over the best single checkpoint that we evaluated, as shown in Table 1.

#### 2.3.2 Ensemble Single Models into One Graph

As the competition requires the final model to be in a single tensorflow graph, it is not viable to ensemble single models’ outputs. Instead, we build ensemble graph at the evaluation/inference stage, and overwrite the (untrained) float16 weights tensor with previously trained float32 single model weights tensors.

Code snippet to build ensemble graph

  with tf.variable_scope("tower"):
result = model.create_model(
model_input,
...,
if FLAGS.ensemble_num> 1:
predictions_lst = [result["predictions"]]
for ensemble_idx in range(1,FLAGS.ensemble_num):
with (tf.variable_scope("model"+str(ensemble_idx))):
result2 = model[ensemble_idx].create_model(
model_input,
...,
predictions_lst.append(result2["predictions"])

if FLAGS.ensemble_num==1:
predictions = result["predictions"]
else:
predictions = 0
for ensemble_idx in range(FLAGS.ensemble_num):
predictions += predictions_lst[ensemble_idx] *
FLAGS.ensemble_wts[ensemble_idx]



To sum up our steps:

1. Train all single models in default float32 precision and average checkpoints.

2. For each potential ensemble model combination, build ensemble graph as above in float16 precision without training.

3. Populate ensemble graph’s float16 weight tensors with single model’s float32 trained weights.

4. Tune ensemble combinations and coefficients based on validate GAP.

## 3 Experiment

We trained and evaluated 28 models with same architecture but different cluster size and hidden size mentioned in 2.1. We use the convention K-H to denote model with cluster size and hidden size . If a model has larger size but same or worse score than another model, we mark it an inferior model and eliminate it from the candidate list for later ensemble. There are 18 models left on the list, which is detailed in Table 1. The 10 eliminated models are K20-H1600, K64-H1024, K150-H600, K128-H512, K16-H1024, K32-H400, K128-H1024, K8-H1024, K32-H800 and K8-H800.

We then tried out different combinations of single models, subject to the model size constraint of 1GB uncompressed. Details of ensemble models are shown in Table 2. Our final selected 7th place model is the YHLS ensemble with ensemble weights = , see Fig. 2. Figure 2: Illustration of our best ensemble model YHLS, where each letter represents a single model. Kx-Hy in each cell denotes the single model with cluster size K=x and first hidden layer size H=y. GAP reported was evaluated on local validate set and adjusted to be Kaggle public leaderboard equivalent. Model size is reported in each cell. (0.39, 0.26, 0.21, 0.14) are the ensemble weights of each model, respectively.

## 4 Conclusions

In this paper we summarized our 7th place solution to the 2nd YouTube-8M Video Understanding Challenge. We chose the same Gated NetVLAD model architecture and trained 28 models with different hyperparameters and varying sizes. We applied three techniques to ensemble single models into a constrained-size tensorflow graph: averaging checkpoints, float16 compression, and building ensemble graph.

In our experiments, we found that in the Gated NetVLAD model, hidden size can create a bottleneck for information representation. Sacrificing cluster size in exchange for hidden size can achieve better results for constrained-size models. In ensemble, we noticed that more smaller size single models do not always beat fewer larger size single models. The optimal number of models in the ensemble is 3 to 4 in our framework. We believe this is due to the boosting effect of ensemble diminishing when we add too many models. For example, even if the ensemble of two smaller models show better GAP score than a single model with the same total size, after further ensembling with more models , the ensemble may beat ensemble —the boosting effect between and is not as good as between and as some of the model variety boost is already “used” between and .

Had we had more time, we would explore other models and techniques since we had already done a fairly thorough search in gated NetVLAD model’s hyperparameter space and tried nearly all the ensemble combinations. Given more time, we would further experiment 8-bit quantization. Should it work out, we would train models with different architectures such as LSTM, Bag-of-visual-words and Fischer Vector and fit them in the gained extra space in the model. In parallel, we could have tried distillation technique since it gives a boost in performance without needing extra model size.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8269478,"math_prob":0.9321256,"size":23787,"snap":"2020-24-2020-29","text_gpt3_token_len":6105,"char_repetition_ratio":0.11794139,"word_repetition_ratio":0.04764622,"special_character_ratio":0.28334805,"punctuation_ratio":0.19991618,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95571613,"pos_list":[0,1,2,3,4,5,6],"im_url_duplicate_count":[null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-06-04T04:33:01Z\",\"WARC-Record-ID\":\"<urn:uuid:555337d8-bc8e-4a40-80ce-d093f930e7fc>\",\"Content-Length\":\"270141\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:c58592b2-faa6-434e-a05d-fdb0b142f5ce>\",\"WARC-Concurrent-To\":\"<urn:uuid:879576f1-5938-42b4-b284-7745832e4cf8>\",\"WARC-IP-Address\":\"35.155.120.0\",\"WARC-Target-URI\":\"https://deepai.org/publication/constrained-size-tensorflow-models-for-youtube-8m-video-understanding-challenge\",\"WARC-Payload-Digest\":\"sha1:AOBVAKHSFDMYQKEKUFYFUCC5KGTE36BP\",\"WARC-Block-Digest\":\"sha1:WYRYBR5FJVXUPXNKKVKWKLVVR5D7JQUP\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-24/CC-MAIN-2020-24_segments_1590347439019.86_warc_CC-MAIN-20200604032435-20200604062435-00080.warc.gz\"}"}