AI Logic

Architectures

TSN

Updated:

Architecture of TSN. Left: the flow of one stream (the video is split into 3 segments, one snippet is randomly chosen from each, a weight-shared 2D CNN produces scores, a per-class average forms the consensus, which feeds a softmax and a video-level loss). Right: fusion of two streams (the consensus scores of the RGB and optical-flow TSNs are combined by a weighted average with weights 1 and 1.5).

Background and Overview

TSN (Temporal Segment Networks) is a framework that splits a video into several segments of equal length, samples one short snippet from each segment, passes them through the same CNN, and trains at the video level on the average (consensus) of their scores. It was presented at ECCV 2016 by Wang et al. of ETH Zurich, the Chinese University of Hong Kong, and other institutions.

Its foundation is Two-Stream ConvNets. However, Two-Stream ConvNets looked at only one frame (or 10 stacked optical-flow pairs) from a video at each training step and could not use for training the flow of an action that unfolds over several seconds (for example, the run-up, takeoff, and landing of a high jump). Prior work that looked at long time spans fed densely stacked frames, which was computationally heavy and limited the viewable length to about 64–120 frames.

TSN answered this with the following ideas.

  • Neighboring frames are nearly identical, so dense viewing is unnecessary: The whole video is split into KK segments, and only one snippet is chosen from each (sparse sampling). No matter how long the video is, the computation covers only KK snippets.
  • The loss is computed at the video level: The loss is computed on the "consensus" that combines the scores of the KK snippets, so information from the entire video is used in each update.

The paper also compiles good practices for training deep CNNs on limited video data.

  • Input modalities: In addition to RGB, it tried RGB differences and optical flow with camera motion compensated (warped flow).
  • Cross-modality pretraining: The optical-flow network is also initialized from an ImageNet model trained on RGB.
  • Partial BN and dropout: The statistics of Batch Normalization are frozen in all but the first layer to curb overfitting.
  • Data augmentation: Corner cropping, and cropping with varying scale and aspect ratio.

The main results of the paper are 94.2% on UCF-101 and 69.4% on HMDB-51 (averaged over 3 splits), both new state-of-the-art results at the time. The arXiv version states that this approach won the ActivityNet 2016 challenge (classification of untrimmed videos). TSN has since remained a baseline model for video recognition with 2D CNNs, including TSM.

Theory: Training on the Consensus of Per-Segment Snippets

The TSN formulation (Section 3.1 of the paper)

A video VV is split into KK segments of equal length {S1,S2,…,SK}\{S_1, S_2, \dots, S_K\}, and a snippet TkT_k is chosen at random from each segment SkS_k. TSN models this sequence of snippets as follows (Eq. 1).

TSN(T1,T2,…,TK)=H(G(F(T1;W),F(T2;W),…,F(TK;W)))\mathrm{TSN}(T_1, T_2, \dots, T_K) = \mathcal{H}\big(\mathcal{G}(\mathcal{F}(T_1; \mathbf{W}), \mathcal{F}(T_2; \mathbf{W}), \dots, \mathcal{F}(T_K; \mathbf{W}))\big)
  1. Per-snippet scores: F(Tk;W)\mathcal{F}(T_k; \mathbf{W}) is the class score produced from snippet TkT_k by a CNN with weights W\mathbf{W}. The KK snippets share the same weights.
  2. Segmental consensus: G\mathcal{G} combines the KK scores. The consensus GiG_i for class ii is determined only from the scores of the same class as Gi=g(Fi(T1),…,Fi(TK))G_i = g(F_i(T_1), \dots, F_i(T_K)). The paper compared average, max, and weighted average for gg and adopted the average.
  3. Prediction: H\mathcal{H} is a softmax that outputs class probabilities for the whole video.

The loss is the cross-entropy on the consensus G\mathbf{G} (Eq. 2; CC is the number of classes and yiy_i is the ground-truth label).

L(y,G)=−∑i=1Cyi(Gi−log⁡∑j=1Cexp⁡Gj)L(y, \mathbf{G}) = -\sum_{i=1}^{C} y_i \left( G_i - \log \sum_{j=1}^{C} \exp G_j \right)

The gradient of the weights flows through all KK snippets (Eq. 3).

∂L(y,G)∂W=∂L∂G∑k=1K∂G∂F(Tk)∂F(Tk)∂W\frac{\partial L(y, \mathbf{G})}{\partial \mathbf{W}} = \frac{\partial L}{\partial \mathbf{G}} \sum_{k=1}^{K} \frac{\partial \mathbf{G}}{\partial \mathcal{F}(T_k)} \frac{\partial \mathcal{F}(T_k)}{\partial \mathbf{W}}

Therefore, information sampled from the entire video is used in each update. The paper uses K=3K = 3.

Network and inputs (Section 3.2)

  • Network: Inception with Batch Normalization (BN-Inception) is used. It gave better results than GoogLeNet and VGG-16.
  • Two streams: As in Two-Stream ConvNets, the spatial stream takes a single RGB image and the temporal stream takes a stack of consecutive optical-flow fields as a snippet (right of the figure at the top of the article).
  • Additional inputs: Stacked RGB differences between consecutive frames (appearance change) and optical flow with camera motion compensated by a homography (warped flow) were also tried.

Training practices (Section 3.2)

  1. Cross-modality pretraining: Optical-flow values are linearly rescaled to 0–255, and the first-layer weights of an RGB model trained on ImageNet are averaged over the 3 RGB channels and replicated to match the number of input channels of the temporal stream.
  2. Partial BN: After initializing from the pretrained model, the means and variances of all BN layers except the first are frozen. Only the first layer is re-estimated, because the distribution of optical flow differs from RGB.
  3. Dropout: Placed after global average pooling, with a rate of 0.8 for the spatial stream and 0.7 for the temporal stream.
  4. Data augmentation: Inputs are resized to 256 × 340, the crop width and height are chosen randomly from {256,224,192,168}\{256, 224, 192, 168\}, and the crop is resized back to 224 × 224 (scale and aspect-ratio jittering). Crop positions are limited to the 4 corners or the center.

Testing (Section 3.3)

As in Two-Stream ConvNets, 25 snippets are chosen from a video, and scores are computed and averaged over the 4 corner crops, the center crop, and their horizontal flips. The two streams are combined by adding the pre-softmax scores with weights of 1 for spatial and 1.5 for temporal.

Because the snippets share weights, the trained network can be evaluated one frame at a time just like an ordinary 2D CNN. TSN does not add special layers; it is a framework that changes how training is done (where to sample and what the loss is computed on).

Why Sparse Sampling Works

1. Long-range temporal structure can be used for training at low cost

Consecutive frames are nearly identical, so stacking them densely does not add much information for the network. TSN chooses only KK snippets spaced across the whole video, so however long the video is, the beginning, middle, and end are seen together in one update. The computation is only that of KK snippets.

As an everyday analogy, it is like judging "what the story is about" by watching one scene each from the beginning, middle, and end of a film, rather than watching every frame.

2. It reduces the mismatch between the video label and the snippet

Two-Stream ConvNets trained by attaching the whole video's label to a single frame. Even frames that show only part of the action are trained to predict that label, so the model tends to rely on cues such as the background. TSN computes the loss on the consensus of KK snippets, so even if one of them is ambiguous, the other snippets compensate.

In the paper's visualization (class visualization with DeepDraw), the model trained on single frames focused on the water and diving platform for the "diving" class, whereas the model trained with TSN focused on the person and even depicted the posture at each stage of the dive.

3. Practices to curb overfitting with limited data

UCF-101 and HMDB-51 are too small to train a deep CNN from scratch.

  • Cross-modality pretraining: Optical flow has a different distribution from RGB, but averaging and replicating the first-layer weights transfers ImageNet knowledge to the temporal stream as well.
  • Partial BN: BN estimates means and variances from training mini-batches, but with little data the estimates become biased and cause overfitting during transfer. The statistics are therefore frozen, and only the first layer, where the distribution changes greatly, is re-estimated.

RGB differences can be used as a cheap motion representation that does not require computing optical flow. In the paper, combining RGB with RGB differences raised accuracy from 84.5% with RGB alone to 87.3%. However, they can be unstable as a motion representation, and the final combination uses three inputs: RGB, optical flow, and warped flow.

Experimental Results

The paper evaluates on UCF-101 (101 classes, 13,320 videos) and HMDB-51 (51 classes, 6,766 videos). Design comparisons are done on split 1 of UCF-101, and the final comparison with prior work uses the average over 3 splits.

Effect of the training practices (UCF-101 split 1; Table 1 of the paper; BN-Inception without the TSN framework)

Training strategySpatialTemporalTwo-stream
Original Two-Stream (baseline)72.7%81.0%87.0%
From scratch48.7%81.7%82.9%
Pretrain spatial only84.1%81.7%90.0%
+ Cross-modality pretraining84.1%86.6%91.5%
+ Partial BN and dropout84.5%87.2%92.0%

Input modalities (UCF-101 split 1; Table 2 of the paper)

InputAccuracy
RGB84.5%
RGB difference83.8%
RGB + RGB difference87.3%
Optical flow87.2%
Warped flow86.9%
Optical flow + warped flow87.8%
Optical flow + warped flow + RGB92.3%
All four91.7%

Segmental consensus function (UCF-101 split 1; Table 3 of the paper)

Consensus functionSpatialTemporalTwo-stream
Max85.0%86.0%91.6%
Average85.7%87.9%93.5%
Weighted average86.2%87.7%92.4%

Effect of the network and TSN (UCF-101 split 1; Tables 4 and 5 of the paper)

NetworkSpatialTemporalTwo-stream
Clarifai (original Two-Stream)72.7%81.0%87.0%
GoogLeNet77.1%83.9%89.0%
VGGNet-1679.8%85.7%90.9%
BN-Inception84.5%87.2%92.0%
BN-Inception + TSN85.7%87.9%93.5%

Even after all the training practices were applied, the TSN framework added another 1.5 points (92.0% → 93.5%).

Comparison with prior work (average over 3 splits; excerpt from Table 6 of the paper)

MethodHMDB-51UCF-101
iDT + Fisher vectors57.2%85.9%
Two-Stream59.4%88.0%
C3D (3 nets)―85.2%
Two-Stream + LSTM―88.6%
TDD + Fisher vectors63.2%90.3%
LTC64.8%91.7%
KVMF63.3%93.1%
TSN (2 modalities: RGB + flow)68.5%94.0%
TSN (3 modalities: RGB + flow + warped flow)69.4%94.2%

It surpassed the previous best by 3.9 points on HMDB-51 and 1.1 points on UCF-101.

Practical Considerations

Keep the following points in mind when using TSN.

  • The order of snippets is not used: Because the segmental consensus is an average, shuffling the snippets does not change the result. Actions whose meaning depends on order, such as "opening a box" vs. "closing a box", are hard to distinguish. In the TSM paper as well, on Something-Something V1, where temporal relations matter, the accuracy of TSN (ResNet-50, 8 frames) stayed around 20%. On Kinetics, where appearance cues are strong, it reached 70.6%, so the gap depends heavily on the nature of the dataset.
  • Consensus is taken only on the final scores: Snippets do not exchange information in the middle of the CNN. Fine motion relies on the optical flow of each snippet.
  • Computing optical flow is expensive: The accurate two-stream form requires precomputing TV-L1 optical flow. The paper uses the CUDA version in OpenCV.
  • Choosing KK: The paper sets K=3K = 3 following prior work and does not report comparisons with different KK.

Partial BN is a practice for fine-tuning from pretrained weights on small data. It freezes the means and variances of all BN layers except the first, so it does not directly apply when training from scratch on data far from the pretraining data. When implementing it in PyTorch, every call to model.train() puts BN layers back into training mode, so put code inside train() that sets the BN layers to be frozen back to eval() (see the implementation example below).

Comparison with Other Models

Comparing video action recognition models from the same viewpoints gives the following.

ModelConvolutionWhat part of the video it seesTemporal orderOptical flowComputational cost
Two-Stream ConvNets2D1 frame + 10 flow pairs (25 locations averaged at test)Not usedRequiredLight (flow is separate)
C3D3D16 consecutive framesUsed via 3D convolutionNot neededHeavy
TSN2DWhole video split into KK segments, one snippet eachNot used (average)Used (RGB only also possible)Light (flow is separate)
I3D3D64 consecutive framesUsed via 3D convolutionUsed (RGB only also possible)Heavy
TSM2D8–16 frames sampled sparsely, as in TSNUsed via channel shiftingNot neededSame as a 2D CNN
SlowFast3D (partly 2D)A 64-frame clip at two frame ratesUsed via 3D convolutionNot neededModerate

Rough guidelines for choosing:

  • To train on whole videos cheaply with a 2D CNN, or to get a baseline model: TSN is the starting point. It can be used with almost no change to existing image CNN training pipelines.
  • To distinguish actions where temporal order matters: TSM, which keeps TSN's sparse sampling but exchanges information between snippets, improves greatly at the same computational cost.
  • To classify long untrimmed videos: TSN's idea of splitting into segments and sampling also works for long videos such as those in ActivityNet.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
Example implementation of TSN (Wang et al. 2016, Sections 3.1-3.3)
Input: K snippets (N, K, C, H, W)  <- C = 3 for RGB, C = 2L for L stacked flow fields
"""


def sample_segment_indices(num_frames, K=3, train=True):
  """Split the video into K segments of equal length and choose one frame position from each (Section 3.1).
  Random during training, segment center at test time (a simplified version that differs from the paper's 25 locations)."""
  edges = torch.linspace(0, num_frames, K + 1)
  if train:
    offs = torch.rand(K)
  else:
    offs = torch.full((K,), 0.5)
  return (edges[:-1] + offs * (edges[1:] - edges[:-1])).long().clamp(max=num_frames - 1)


def cross_modality_init(conv1_rgb_weight, in_ch):
  """Section 3.2: average the RGB-trained first-layer weights (out, 3, k, k) over the 3 RGB channels
  and replicate them to match the number of input channels of the temporal stream."""
  w = conv1_rgb_weight.mean(dim=1, keepdim=True)
  return w.repeat(1, in_ch, 1, 1)


class TSN(nn.Module):
  def __init__(self, backbone, feat_dim, num_classes, K=3, p_drop=0.8, partial_bn=True):
    super().__init__()
    self.backbone = backbone          # 2D CNN (BN-Inception in the paper); output is (N, feat_dim)
    self.dropout = nn.Dropout(p_drop) # after global average pooling; 0.8 spatial, 0.7 temporal
    self.fc = nn.Linear(feat_dim, num_classes)
    self.K = K
    self.partial_bn = partial_bn

  def forward(self, x):
    n, k = x.shape[:2]
    # pass the K snippets through the CNN with the same weights W
    scores = self.fc(self.dropout(self.backbone(x.flatten(0, 1))))  # (N*K, classes)
    # segmental consensus G: average the scores of the same class over K (before softmax)
    return scores.view(n, k, -1).mean(dim=1)

  def train(self, mode=True):
    super().train(mode)
    if mode and self.partial_bn:
      # partial BN: freeze the means and variances of all BN layers except the first (Section 3.2)
      bns = [m for m in self.backbone.modules() if isinstance(m, nn.BatchNorm2d)]
      for bn in bns[1:]:
        bn.eval()
    return self


backbone = nn.Sequential(   # a small CNN just to run the example (in practice, e.g., BN-Inception trained on ImageNet)
  nn.Conv2d(3, 32, 7, stride=2, padding=3), nn.BatchNorm2d(32), nn.ReLU(),
  nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
  nn.AdaptiveAvgPool2d(1), nn.Flatten(),
)
model = TSN(backbone, feat_dim=64, num_classes=101, K=3)
criterion = nn.CrossEntropyLoss()   # Eq. 2: softmax and cross-entropy on the consensus G

model.train()   # partial BN is also enabled
idx = sample_segment_indices(num_frames=300, K=3, train=True)
clips = torch.randn(2, 3, 3, 224, 224)   # (N, K, C, H, W); in practice, feed the frames at positions idx
loss = criterion(model(clips), torch.tensor([5, 17]))
loss.backward()   # the gradient flows through all K snippets (Eq. 3)

model.eval()    # testing: dropout off, BN uses the learned statistics
with torch.no_grad():
  print(model(clips).shape)   # torch.Size([2, 101])

# Fusion of the two streams (Section 3.3): add the pre-softmax scores with weights 1 : 1.5
# score = rgb_tsn(rgb_snippets) + 1.5 * flow_tsn(flow_snippets)

FAQ

Q. How does TSN differ from Two-Stream ConvNets?
A.

The network shape (two streams, RGB and optical flow) is the same; the training method differs. Two-Stream ConvNets trains on only one frame (or 10 flow pairs) chosen from a video. TSN splits the video into KK segments, chooses one snippet from each, and computes the loss on the average (consensus) of their scores, so information from the whole video is used in each update. Together with the switch to BN-Inception, cross-modality pretraining, partial BN, and other practices, accuracy on UCF-101 rose from 88.0% to 94.2%.

Q. Why is the average used for the segmental consensus?
A.

The paper compared average, max, and weighted average, and the average gave the best two-stream result (93.5% on UCF-101 split 1). The paper does not state the reason, but from the equations, with max the gradient flows only to the snippet with the highest score for each class. With the average, the gradient flows to all KK snippets, so information from the whole video is used for training.

Q. What is partial BN?
A.

It is a method that, after initializing from a pretrained model, freezes the means and variances of all Batch Normalization layers except the first. Re-estimating BN statistics on small data gives biased estimates and causes overfitting. Only the first layer is re-estimated, because the distribution of optical flow differs from that of RGB images. In the paper, together with dropout, it raised the two-stream accuracy on UCF-101 from 91.5% to 92.0%.

References

  1. Wang, L., Xiong, Y., Wang, Z., Qiao, Y., Lin, D., Tang, X., & Van Gool, L. (2016). Temporal Segment Networks: Towards Good Practices for Deep Action Recognition. ECCV 2016. arXiv:1608.00859.
  2. yjxiong/temporal-segment-networks (the authors' released code).
  3. Simonyan, K., & Zisserman, A. (2014). Two-Stream Convolutional Networks for Action Recognition in Videos. NIPS 2014. arXiv:1406.2199.
  4. Lin, J., Gan, C., & Han, S. (2019). TSM: Temporal Shift Module for Efficient Video Understanding. ICCV 2019. arXiv:1811.08383.