{'fraction_non_alphanumeric': 0.03514470274807489, 'fraction_numerical': 0.012335316229334696, 'mean_word_length': 4.690965732087228, 'pattern_counts': {'":': 0, '<': 1, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Hierarchical Modular Network for Video Captioning

Video captioning aims to generate natural language descriptions according to the content, where representation learning plays a crucial role. Existing methods are mainly developed within the supervised learning framework via word-by-word comparison of the generated caption against the ground-truth text without fully exploiting linguistic semantics. In this work, we propose a hierarchical modular network to bridge video representations and linguistic semantics from three levels before generating captions. In particular, the hierarchy is composed of: (I) Entity level, which highlights objects that are most likely to be mentioned in captions. (II) Predicate level, which learns the actions conditioned on highlighted objects and is supervised by the predicate in captions. (III) Sentence level, which learns the global semantic representation and is supervised by the whole caption. Each level is implemented by one module. Extensive experimental results show that the proposed method performs favorably against the state-of-the-art models on the two widely-used benchmarks: MSVD 104.0% and MSR-VTT 51.5% in CIDEr score.


Introduction
Video captioning aims to automatically generate natural language descriptions from videos, which plays an important role in numerous applications, such as assisting visually-impaired people, human-computer interaction, and video retrieval [7,27,36,42,43,45,49]. Despite recent advances in this field, it remains a challenging task as a video usually contains rich and diverse content, but only some information is relevant to caption (e.g., two or three out of many objects are captured in a caption). Figure 1. To effectively bridge video content and linguistic caption, we propose to supervise video representation learning in a three-level hierarchical structure, i.e., the entity level, the predicate level, and the sentence level.
Existing methods aim to learn effective video representations to generate captions via recurrent decoders, which can be broadly categorized into two lines of work. The first one focuses on designing complex video encoders to learn better video representations [1,5,6,26,44,50,51]. For example, STG-KD [26] and ORG-TRL [51] build object relation graphs to reason the spatial and temporal relations between video objects. While GRU-EVE [1] applies Short Fourier Transform [25] to embed temporal dynamics in visual features, POS+CG [44] develops a cross gating block to fuse appearance and motion features and make a comprehensive representation. However, the optimization objectives of these methods are computed word-by-word as captions generating, disregarding the relevance between video representations and their linguistic counterpart. The other one focuses on narrowing the semantic gap between video representation and linguistic captions ahead of generating captions [28,35,52]. For example, Pan et al. [28] learn to align the global representation of a video to the embedding of a whole caption. In contrast, Shen et al. [35] and Zheng et al. [52] associate nouns and verbs with visual features to explore the video-language correspondence on a fine-grained level. These approaches are able to generate more accurate captions as more representative video embedding is learned. However, they either focus on global sentence correspondence or local word correspondence, which disregard finegrained details or global relevance.
In this work, we propose a hierarchical modular network to address the issues mentioned above. Our model aims to learn three kinds of video representations supervised by language semantics at different hierarchical levels as shown in Figure 1: (I) Entity level, which highlights objects that are most likely to be mentioned in captions and is supervised by entities 1 in the caption. (II) Predicate level, which learns the actions conditioned on highlighted objects and is supervised by the predicate in the caption. (III) Sentence level, which learns the global video representation supervised by the whole caption. Each level is implemented by one module. The motivation of our design is that objects usually serve as the cornerstone of a video caption, which can be the subject or object of an action as well as modifiers of subject and/or object. Instead of learning the visual representation of verbs along, we propose to learn video representation of predicates (verb+noun). This helps reduce the correspondence errors from a multi-meaning verb to a specific video action embedding, such as the play in playing soccer and playing the piano. The global video content embedding supervised by the embedding of a whole caption enables the generated caption to have a reasonable meaning.
It is worth noting that we propose a novel entity module. This module takes all the pre-extracted objects of a video as input and outputs a small set of principal objects that are most likely mentioned in a caption. Motivated by the success of DETR [3] for object detection, our entity module is designed with a transformer encoder-decoder architecture. In contrast to DETR, our queries are enhanced by video content and supervised by entities in captions, which enables the model to select principal objects according to video scenarios.
The contributions of this paper are summarized below: • We propose a hierarchical modular framework to learn multi-level visual representations at different granularity by associating them with their linguistic counterparts: the entity, predicate, and sentence. • We propose a transformer-based entity module to learn to select principal objects that are most likely to be mentioned in captions. • Our method performs favorably against the state-1 Note that entities are different from nouns. Nouns contain abstract nouns, such as happiness and hunger., while entities consist of object names, such as onion and car.

Related Work
From Template-based to CNN-based Methods. There are a number of methods have been proposed for the video captioning task. Kojima et al. [18] and Krishnamoorthy et al. [20] propose to first generate words for objects and actions, and then fit predicted words into predefined sentence templates to generate captions. However, templatebased methods are hard to generate flexible descriptions. Inspired by the success of RNN and CNN, the encoderdecoder structure is widely utilized to generate descriptions with flexible syntactic structure [27,43,45]. In [42], Venugopalan et al. learn video representations by performing mean-pooling over CNN features of each frame, and exploit an LSTM [14] to generate captions. On the other hand, Yao et al. [49] design a temporal attention mechanism to aggregate relevant video segments given the state of textgenerating RNN, modeling the global temporal structure of videos. In addition to the most frequently used image and motion features, Hori et al. [15] and Xu et al. [48] exploit audio features to enrich the video representation. In [7], Chen et al. propose a PickNet to select informative frames from the video, removing redundant visual information. Recently, Wang et al. [46] and Pei et al. [30] enhance the captioning quality by designing a memory network to organize multiple visual features. Utilizing Detected Objects. Objects play an important role in generating captions, which are usually extracted via pre-trained object detectors (e.g. YOLO9000 [31], Faster-RCNN [33], Mask RCNN [13]). Significant efforts have been made to use object information of videos for captions. In [50], Zhang et al. utilize a GRU [8] to capture object dynamic information from temporal trajectories. Aafaq et al. [1] exploit object labels (predicted by object detectors) to enhance the semantics of visual representation. On the other hand, Zheng et al. [52] adopt an dot-product attention mechanism to help determine the interactions between objects. In addition, Pan et al. [26] and Zhang et al. [51] employ graph convolutional networks [17] to perform relational reasoning among detected objects to enhance objectlevel representation. These approaches can generate more accurate captions as detailed video information is mined. However, all detected objects are used in these methods. As usually only a small set of objects are mentioned in captions, the large number of redundant objects may negatively affect the captioning performance. In contrast, we propose an entity module to highlight principal objects that are most likely to be mentioned in the caption in this work, reducing the noise brought by redundant objects. Transformer in Vision. The success of transformer models [9,23,40] in natural language processing has attracted  much interest in the computer vision community. Several methods have shown the effectiveness of transformers for vision tasks, such as image classification [10,24,39], object detection [3,54], video understanding [11,37], and semantic segmentation [53]. Motivated by DETR [3], which adaptively learn queries to detect objects, in this work we develop a transformer-based entity module to highlight principal objects out of a large number of candidates. Experiments and ablation studies show the effectiveness of this design.

Method
As shown in Figure 2, our model follows the conventional encoder-decoder paradigm, where our Hierarchical Modular Network (HMN) serves as the encoder. Our HMN consists of the entity, predicate, and sentence modules. Equipped with language heads, these modules are designed to bridge video representations and linguistic semantics from three levels. Our model operates as follows. First, taking all detected objects as input, the entity module outputs the features of principal objects. The predicate module encodes actions by combining features of principal objects and the video motion. Next, the sentence module encodes a global representation for the entire video content considering the global context and features of previously generated objects and actions. Finally, all features are concatenated together and fed into the decoder to generate captions.

Entity Module
Given a sequence of video frames, we uniformly select T frames as keyframes and collect short-range video frames  around keyframes as 3D cuboids. We exploit a pre-trained object detector [33] to capture object regions from each keyframe, and cluster these regions according to appearance and Intersection over Union (IoU) among bounding boxes. Then we apply the mean-pooling operation to these clusters to obtain the initial object

Hungarian matching
where L and d o denote the number of video objects and size of object features. As there are a large number of objects in a video, but only some are mentioned in captions, we design the entity module to learn to highlight these principal objects adaptively. Architecture. Figure 3 illustrates the main architecture of our entity module, which consists of a transformer encoder and transformer decoder. This design is motivated by DETR [3], which utilizes a transformer encoder-decoder architecture to learn a fixed set of object queries to directly predict object bounding boxes for the object detection task. Instead of simply detecting objects, we aim to determine the important ones in the video. Due to significant difference between these two tasks, a simple application of DETR architecture performs poorly (see Section 4.4). As the key of DETR is to learn queries, we design our own queries as detailed later.
The encoder maps input objects O to a set of representations: where o i ∈ R d model . Note that unlike conventional transformers, we discard positional encodings of objects because the object spatial location is meaningless after we apply mean-pooling on object features. To enable the decoder to highlight principal objects, our decoder takes three types of inputs: is randomly initialized N parameters for queries. {v} ×N are N identical video content vectors to put each query q i into a proper context and thus to facilitate decoding N video-specific principal object features. To construct the video content vector v, we first utilize the pre-trained 2D CNNs [38] and pre-trained 3D CNNs [12] to extract the context features C = {c i } T i=1 from keyframes, and motion features M = {m i } T i=1 from 3D cuboids. Then, C and M are concatenated and fed into a BiLSTM to generate a set of hidden ). Next, we aggregate H by max-pooling to obtain an embedding v = maxpool(H) which represents video content.
As the decoder output, principal object features E are later fed to the predicate and sentence modules, as well as the language head as shown in Figure 2. The language head projects E to linguistic semantic space via a fully-connected layerĒ whereē i ∈ R ds . This language head is supervised by embeddings of entities from captions as detailed in the next sub-section. Loss function. We exploit the entities in captions to supervise our entity module. Specifically, we first obtain the "synonymy label" in WordNet 2 of each noun in groundtruth captions. And then, we choose nouns with labels "object.n.01", "causal agent.n.01", and "matter.n.03" as entities, discarding abstract nouns.
Assume that M entities are extracted from a caption, we employ the pre-trained SBERT [32] as text encoder to compute the entities embeddings N = {n i } M i=1 , where n i ∈ R ds . We set N larger than the typical number of entities in captions, and pad N to size N with ∅ (no entity). Then, we search for an optimal assignmentσ between N andĒ with minimum distance cost: where the Ω N is the assignment search space for N elements, and Dist(n i ,ē σ(i) ) is a pair-wise matching cost between the entity embedding n i and predicted linguistic embeddingē σ(i) by This optimal assignment is computed efficiently with Hungarian algorithm [21] as in DETR [3]. Finally, according to the optimal assignmentσ, we optimize our entity module by minimizing the distance between N andĒ:

Predicate Module
Our predicate module is designed to learn action representations that bridge the video action information and the predicate of the caption. As a predicate usually consists of a verb and its recipient, our predicate module concatenates the initial motion features M = {m i } T i=1 and motionrelated object features M e = {m e i } T i=1 as input. For each motion m i , we compute its motion-related object features m e i by attentively summarizing principal object features E via where α i,k is the weight of k-th object e k regarding i-th motion; W a , w a , U a and b a are learnable parameters. Then, we use a bi-directional LSTM to encode actions: where a i ∈ R d model . The action features A are later used as inputs for the sentence module and predicate language head. Formulated as a fully-connected layer, the predicate language head projects video action to linguistic semantic space:ā = FC(maxpool(A)) whereā ∈ R ds . Loss function. We exploit the predicate of ground-truth captions to supervise our predicate module. Likewise, we use SBERT [32] to encode the predicate into embedding p ∈ R ds . Then, our predicate module is optimized by minimizing the distance between p andā:

Sentence Module
Our sentence module is designed to learn global video representations that bridge global visual content and the entire linguistic caption. Since a caption comprises entities, the predicate, and other context information, our sentence module takes initial video context features ,and contextrelated object features C e = {c e i } T i=1 as input. We obtain c a i and c e i by attentively summarizing action features A = {a i } T i=1 and principal object features E = {e i } N i=1 according to video context c i . Here we take c a i as an example: where β i,k is the weight of the k-th action regarding the i-th context; w g , W g , U g and b g are learnable parameters. Then, we compute the global video features: where g i ∈ R d model . The global video feature G is later used as input of the caption generator and the language head of the sentence module. The language head of this module is implemented via a fully-connected layer. It takes G as input and predicts global video linguistic embedding under supervision of the embedding of captionsḡ = FC(maxpool(G)), whereḡ ∈ R ds . Loss function. We exploit the embedding of the whole caption to supervise the sentence module. Similarly, the caption embedding s ∈ R ds is computed by the pretrained SBERT. Then we minimize the distance between s andḡ to optimize our sentence module:

Description Generation
We employ an LSTM as our description generator to produce accurate captions in steps. To generate accurate descriptions for videos, our description generator takes all three levels of video representations, their linguistic predictions, and the previous word w t−1 as inputs where E(w t−1 ) ∈ R dw is the word embedding of w t−1 , and d w is the embedding size.ĝ l t ,â l t , andê l t are concatenation of visual features and linguistic predictions, i.e., g l t = [g l t ;ḡ],â l t = [a l t ;ā],ê l t = [e l t ;ē l t ].ḡ andā are predicted linguistic embeddings of global content and actions as described in Section 3.3 and Section 3.2. g l t , a l t , e l t , and e l t are obtained via attentively summarizing G, A, E, and entity linguistic predictionĒ according to the history hidden state h lang t−1 . These four representations are computed in a similar way. Here we take e l t as an example: where γ t,k is the weight of object e k at the t-th decoding step; and w d , W d , U d and b d are learnable parameters. According to the current hidden state of LSTM h lang t , the probability distribution P t over a vocabulary of D words is computed by a fully-connected layer and the softmax operation P t = softmax(FC(h lang t )).
Loss function. Given a video with the ground-truth words [w 1 , . . . , w Ls ], where L s is the caption length, we compute the Cross-Entropy loss to optimize our description generator: where δ(w t ) ∈ R D is the one-hot encoding of word w t . However, the long-tailed word distribution problem 3 in the video captioning corpus likely causes training issues with unbalanced data. To alleviate this problem, Zhang et al. [51] propose a plug-in method, where the abundant linguistic knowledge is transferred from a pretrained external language model (ELM) to the description generator. Given the previous words w <t , the probability distribution of ELM at time step t is: To transfer the knowledge from ELM to the description generator, the KL divergence between P t and Q t is minimized during training: where Q d t and P d t denote the d-th element of Q t and P t . In this work, we treat Q t as "soft target" of our description generator, and use D KL as L sof t . More details about the "ELM" and "soft-target" can be found in [51].

Training
Our model is trained in an end-to-end fashion via optimizing the sum of all losses

Datasets
MSVD is a widely-used video captioning dataset composed of 1970 short video clips collected from YouTube. Each clip is annotated with up to 40 English sentences. Similar to existing methods [6,26,51,52], we take 1200 video clips for training, 100 clips for validation, and 670 clips for testing. MSR-VTT is a large-scale dataset for video captioning. It is collected from a commercial video website and covers the most diverse visual contents so far. MSR-VTT contains 10k video clips from 20 categories, such as music, people, and gaming. Each video clip has 20 English captions, leading to total 28k unique words. We use the same setup as existing methods [6,26,51,52] for experiments (6513, 497, and 2990 videos for training, validation and testing).

Implementation Details
Feature Extraction and Text Processing. We uniformly sample T = 15 clips for each video. Each clip consists of 16 consecutive frames. We take the 8-th frame of each clip as keyframe and detected 10 objects for each keyframe. Similar to most recent methods [1,5,6,51,52], we extract context features using the InceptionResNetV2 [38] model and motion features using the C3D [12] model. In addition, we use Faster-RCNN [33] pretrained on Visual Genome [19] to detect object regions. All the abovementioned visual features are projected to a 512-dimension space before being fed into our model. Likewise, the dimension of encoded visual features d model is set to 512.
For captions, we first remove punctuations and convert all letters into lowercase. Captions are truncated at 20 words and tokenized. We exploit off-the-shelf Constituency Parsing tools provided by AllenNLP 4 to extract nouns and the predicate from the processed caption, where we utilize the WordNet to distinguish entities from nouns as described in Section 3.1. The embedding size d s of entities, predicates, and sentences is set to 768 using the off-the-shelf pre-trained SBERT [32]. The size of word embedding d w is set to 300. Other details. We set the number of queries N in Eq.(2) to 8 for our entity module. Both the encoder and decoder of the entity module have 2 transformer layers for MSVD (3 for MSR-VTT), 8 attention heads, and 512 hidden state size. Empirically, λ e , λ p , λ s , and λ sof t are set to 0.6, 0.3, 1.0, and 0.5 respectively. We adopt the Adam [16] optimizer with a learning rate of 1e-4 to optimize our model. The batch size is set to 64, and the training epochs is set to 20. The hidden size of description generator is set to 512. During testing, we use beam search with size 5 to generate captions. Our entire system is implemented with PyTorch and all experiments are conducted on 1 × RTX-2080Ti GPU.

Comparison to State-of-The-Art Methods
We evaluate the proposed model against the state-of-theart methods. The main results are presented in Table 1. Our method achieves the best performance on the MSVD benchmark in terms of all the four metrics. In particular, our method achieves 59.2 of BLUE@4 (with +2.3 improvement) and 104.0 of CIDEr (with +5.5 improvement). On the MSR-VTT benchmark, our method achieves the best results on 3 out of 4 metrics. Note that CIDEr captures human judgment of consensus better than other metrics [41]. The significant improvements under CIDEr on both benchmarks demonstrate that our model can generate semantically more accurate captions.
Note that GRU-EVE, STG-KD and ORG-TRL focus on designing complex video encoders to learn video representations, but leave the video-language relevance unexploited. SAAT associates the subject, verb, and object with visual information, focusing on local word correspondence. However, our model outperforms them by a significant margin (+8.8∼25.9 of CIDEr on MSVD) via jointly modeling the video-language correspondence at three different levels, which indicates the advantage of further exploring the corresponding relationship between the video and sentence.

Ablation Study
Effectiveness of Proposed Modules. We evaluate the effectiveness of each module by removing them and retraining the model. The results are shown in the first group of Table 2. All the proposed modules contribute significantly to the overall performance. The entity module contributes the most, followed by the sentence and predicate modules.
Effectiveness of Links Between Modules. In our model, we adapt side connections between modules. To evaluate their effectiveness, we cut off such side connections separately. We use "cut e2p" to denote removing the connection between the entity module and the predicate module, "cut e2s" for removing the connection between the entity module and the sentence module, and "cut p2s" for removing the connection between the predicate module and the sentence module.
The results are presented in the second group of Table 2. The performance drops without these side connections, which indicates their contribution to the overall performance. Compared to the performance when removing each module completely, the performance is relatively better. This indicates that the three modules themselves contribute more than the connection design between them.
Noun. v.s. Entity and Verb. v.s. Predicate During the training, we supervise the entity and predicate modules with entities and the predicate, respectively. Here we analyze the alternatives by replacing the entity supervision with broader noun supervision, and replacing predicate with verb supervision. The results are presented in the third group of Table 2. The alternative approaches perform worse than our final model, which indicates entities and the predicate provide better supervisions for video captioning.  Figure 5. Too many or Too few principal object queries can degrade the performance. This is because too many queries may introduce noisy objects and too few queries cannot provide sufficient information.

Qualitative Results
We show some qualitative results in Figure 4. The first row shows attended objects by our entity module. A clearer Ground-truth: two men competing in a ping pong match Ours: two men are playing a game of ping pong Ground-truth: a band on stage is singing and playing Ours: a band is performing on stage Ground-truth: a race car is driving down a track Ours: a person is driving a car on a track Ground-truth: a person is playing with a rubicks cube Ours: a person is solving a rubiks cube  region denotes a higher attention weight. The second row shows the keyframes for reference. As shown in the figure, our model can generate high-quality captions. The regions of principal objects can be chosen correctly most of the time, which shows the entity module has the ability to distinguish principal objects from all the detected objects. We also note that the entity module is able to neglect some redundant frames. For instance, the example at the top-left shows that our entity module mainly focuses on the two ping-pong players rather than those audiences in the first frame. Similarly, in examples at the top-right and bottomleft, our entity module ignores the objects that appeared in the last frames because their content is not closely related to the video caption. Due to space limitation, more qualitative results are placed in supplementary materials.

Limitations
Similar to existing methods [28,34,52], our approach is suitable for single-action videos. However, there exist many multi-action videos in the MSR-VTT dataset. For instance, a man walks in a room and talks to others has two separate actions, i.e., walks in a room and talks to others. Existing methods and the proposed model are not able to handle these complex scenes that require multiple predicates. This is also the main reason why the improvement of our model on MSR-VTT is not as significant as that on MSVD.

Conclusion
In this paper, we proposed a hierarchical modular network for video captioning, which bridges video representations and linguistic semantics from three levels: entity level, predicate level, and sentence level. By constructing three modules and associating them with the their linguistic counterparts, we can obtain effective visual representations for captioning. Furthermore, our entity module is able to identify principal video objects that carry important semantic meanings without processing all mundane ones for generating accurate captions. Our proposed model has achieved the state-of-the-art performance on both MSVD and MSR-VTT benchmarks. Extensive experiments and qualitative results have demonstrated the effectiveness of each module.