AI Logic

Architectures

TSM

Updated:

Architecture of TSM. Left: the operation that shifts part of the channels along the time axis (1/8 of the channels are shifted one frame forward and another 1/8 one frame backward, while the remaining 3/4 are left unchanged; values shifted out are discarded and empty slots are filled with 0). Right: how it is inserted into a 2D CNN (the shift is placed inside the branch of each residual block of ResNet-50, before the 2D convolution, while the identity mapping carries the original features; at the end, the per-frame scores are averaged).

Background and Overview

TSM (Temporal Shift Module) is a module that mixes information between neighboring frames simply by shifting part of the channels of 2D CNN features by one frame forward and backward along the time axis. The shift involves no multiplications and no parameters, so it achieves temporal modeling close to a 3D CNN at the same computational cost as a 2D CNN. It was presented at ICCV 2019 by Lin, Gan, and Han of MIT and the MIT-IBM Watson AI Lab.

In video recognition, the order of frames matters. "Opening a box" and "closing a box" have opposite meanings when the order is reversed. Earlier approaches each had trade-offs:

  • 2D CNNs (such as TSN): Computation is light, but frames are processed independently and only averaged at the end, so temporal order cannot be captured.
  • 3D CNNs (such as C3D and I3D): Time and space can be learned jointly, but computation is heavy and unsuitable for real-time processing on edge devices.

TSM views convolution as two parts, "shifting" and "multiply-accumulate"; it performs only the shift along the time axis and leaves the multiply-accumulate to the following 2D convolution. The main results of the paper are as follows.

  • On Something-Something V1, where temporal relations matter, it raised TSN (2D) from 20.5% to 47.3% (8 frames, same computation). At the time of publication it ranked first on this dataset's leaderboard.
  • It was about 10 times faster than I3D with a 3D ResNet-50 on a P100 GPU (17.4 ms vs. 165.3 ms per video), with higher accuracy.
  • A unidirectional version that does not use future frames enables real-time online video recognition, at 13 ms per frame on a Jetson Nano.

Even on datasets with strong appearance cues such as Kinetics, it improved on TSN by 3.5 points (70.6% → 74.1%).

Theory: Replacing Temporal Convolution with Shifting

Splitting convolution into "shift" and "multiply-accumulate" (Section 3.1)

A 1D convolution with kernel size 3 (weights W=(w1,w2,w3)W = (w_1, w_2, w_3)) can be written as follows.

Yi=w1Xi−1+w2Xi+w3Xi+1Y_i = w_1 X_{i-1} + w_2 X_i + w_3 X_{i+1}

This is equivalent to shifting the input by −1,0,+1-1, 0, +1 (Eq. 1) and then multiplying by the weights and summing (Eq. 2).

Xi−1=Xi−1,Xi0=Xi,Xi+1=Xi+1X^{-1}_i = X_{i-1}, \quad X^{0}_i = X_i, \quad X^{+1}_i = X_{i+1} Y=w1X−1+w2X0+w3X+1Y = w_1 X^{-1} + w_2 X^{0} + w_3 X^{+1}

The shift requires no multiplications. TSM performs only this shift along the time axis and folds the multiply-accumulate into the following 2D convolution, which computes it jointly along the channel dimension. As a result, neither computation nor parameters increase compared with a 2D CNN.

Bidirectional shift (left of the figure at the top of the article)

Let the video features be A∈RN×C×T×H×WA \in \mathbb{R}^{N \times C \times T \times H \times W} (batch, channels, time, height, width).

  1. Shift part of the channels one step forward in time (each time step receives the value from the next time step).
  2. Shift another part one step backward in time (each time step receives the value from the previous time step).
  3. Leave the remaining channels unchanged.
  4. Discard the values shifted out and fill empty slots with 0.

The proportion of shifted channels is 1/4 in total (1/8 in each direction). After the shift, the features at each time step contain information from the neighboring time steps, so the next 2D convolution acts like a temporal convolution with kernel size 3. Each TSM inserted widens the temporal receptive field by 2.

Where to insert it (Sections 3.3 and 4.1; right of the figure at the top of the article)

The shift is inserted inside the residual branch (before the convolution) of each residual block of ResNet-50. The identity mapping (shortcut) carries the unshifted features as they are. The overall pipeline is the same as TSN: TT frames (8 or 16) are sparsely sampled from the video, a 2D CNN produces a score for each frame, and the scores are averaged.

Unidirectional shift for online use (Section 4.2)

Future frames are not available in real-time processing, so only the shift from past to present is used. During inference, the first 1/8 of the features of each residual block is kept in memory, and for the next frame the first 1/8 of the current features is replaced with those cached values (7/8 from the current frame, 1/8 from the previous frame). There is no extra computation, and the required memory for ResNet-50 is 0.9MB.

Training setup (Section 5.1)

  • Kinetics: 100 epochs, learning rate 0.01 (multiplied by 0.1 at epochs 40 and 80), weight decay 10−410^{-4}, batch size 64, dropout 0.5.
  • Other datasets use half the epochs. Most are fine-tuned from ImageNet weights; UCF-101 and HMDB-51 are small, so they are fine-tuned from Kinetics weights with BN frozen.

Why Naive Shifting Does Not Work

In image classification, spatial shift operations (Shift) were already in use. However, the paper showed that applying them directly along the time axis (shifting all channels) causes two problems. The two design choices of TSM address them.

1. Data movement is slow → shift only part of the channels

The shift has no multiplications but moves data in memory. Features in video networks are large 5D tensors, so the time for this movement cannot be ignored. Shifting all channels made inference 13.7% slower on CPU and 12.4% slower on GPU. Shifting only 1/8 keeps the overhead to about 3%.

2. Information of the current frame is lost → shift inside the residual branch

The information in the shifted channels disappears from the current frame. Shifting directly before the convolution (in-place) impairs the 2D CNN's ability to learn spatial features; shifting all channels was 2.6 points worse than TSN. Shifting inside the residual branch lets the identity mapping carry the current frame's information unchanged, so spatial features are not impaired.

The shift proportion is also a trade-off. Too little gives insufficient temporal reasoning, and too much reduces the ability to learn spatial features. In the comparison on Kinetics (Figure 2b of the paper), shifting inside the residual branch was better than in-place shifting at every proportion, and 1/4 (1/8 in each direction) was the best.

As an everyday analogy: if everyone passes their notes to the next seat, nothing is left in their own hands; but if each person swaps only 1/8 of the edge of their notebook with the person in front and another 1/8 with the person behind, they keep their own content while also learning what their neighbors have.

TSM consists only of 2D CNN operations, so it runs fast as is on frameworks and edge hardware optimized for 2D CNNs, such as CuDNN and TVM. In the paper, TSM was also faster and more accurate than a model that replaces the temporal operation with a 3 × 1 × 1 convolution (an I3D-style replacement).

Experimental Results

Improvement over a 2D CNN (TSN) (ResNet-50, 8 frames; evaluated with 10 clips for Kinetics and 2 clips for the others; Table 1 of the paper)

DatasetTemporal relationTSN top-1TSM top-1Gain
KineticsWeak70.6%74.1%+3.5
UCF-101Weak91.7%95.9%+4.2
HMDB-51Weak64.7%73.5%+8.8
Something-Something V1Strong20.5%47.3%+28.0
Something-Something V2Strong30.4%61.7%+31.3
JesterStrong83.9%97.0%+11.7

With the same computation, the gain was larger on datasets where temporal relations matter more.

Different backbones (Kinetics top-1; Table 3 of the paper)

BackboneTSNTSMGain
MobileNetV266.5%69.5%+3.0
ResNet-5070.7%74.1%+3.4
ResNeXt-10172.4%76.3%+3.9
ResNet-50 + Non-local74.6%75.7%+1.1

Comparison on Something-Something V1 (center crop, 1 clip; excerpt from Table 2 of the paper)

ModelBackboneFramesFLOPs (per video)ParamsVal top-1
TSNResNet-50833G24.3M19.7%
TRN-MultiscaleResNet-50833G31.8M38.9%
ECOBNInception + 3D ResNet-181664G47.5M41.4%
I3D3D ResNet-5032 × 2 clips153G × 228.0M41.6%
Non-local I3D3D ResNet-5032 × 2 clips168G × 235.3M44.4%
TSMResNet-50833G24.3M45.6%
TSMResNet-501665G24.3M47.2%

The 8-frame TSM was 1.2 points higher than Non-local I3D at about one-tenth of the computation.

Speed (NVIDIA Tesla P100; latency at batch size 1, throughput at batch size 16; Table 5 of the paper)

ModelFLOPsParamsLatencyThroughputSomething V1Kinetics
I3D (3D ResNet-50)306G35.3M165.3 ms6.1 videos/s41.6%―
ECO (16 frames)64G47.5M30.6 ms45.6 videos/s41.4%―
I3D (inflating only 1×1 convolutions)33G29.3M25.8 ms42.4 videos/s―73.3%
Replaced with 3 × 1 × 1 convolution48G33.0M28.0 ms37.9 videos/s44.9%―
TSM (8 frames)33G24.3M17.4 ms77.4 videos/s45.6%74.1%
TSM (16 frames)65G24.3M29.0 ms39.5 videos/s47.2%74.7%

Online version (Table 6 of the paper)

ModelLatency per frameKineticsUCF-101HMDB-51Something
TSN4.7 ms70.6%91.7%64.7%20.5%
+ Offline TSM―74.1%95.9%73.5%47.3%
+ Online TSM4.8 ms74.3%95.5%73.6%46.3%

Even the unidirectional version that does not use future frames reached almost the same accuracy as the offline version, with less than 0.1 ms of added latency per frame. On UCF-101, it reached about 90% accuracy after seeing only the first 10% of a video.

Practical Considerations

Keep the following points in mind when using TSM.

  • A shift proportion of 1/4 is a good guideline: In the paper's comparison, shifting 1/4 in total (1/8 in each direction) inside the residual branch was the best, and shifting all channels impaired spatial features.
  • Use the same number of input frames for training and testing: The shift rearranges the TT frames within a batch along the time axis, so the number of frames (segments) must be fixed when building the model and the same number must be fed at test time.
  • The offline version uses future frames: The bidirectional shift also uses features from the next time step, so use the unidirectional version for real-time processing. The unidirectional version dropped by 1 point on Something-Something, where temporal relations are strong.
  • The view is limited to the TT sampled frames: As with TSN, frames are sampled sparsely, so if the sampled frames are far apart, there is a large time gap between neighboring "time steps".

Even with the same computation (FLOPs), actual speed depends on the hardware. The shift has no multiplications but incurs data movement; shifting all channels was 13.7% slower on CPU. TSM's speed relies on the small shift proportion and on 2D operations being optimized on the hardware. When deploying it on your own hardware, measure latency and throughput rather than FLOPs.

Comparison with Other Models

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

ModelConvolutionHow temporal information is mixedComputationOptical flowOnline processing
Two-Stream ConvNets2DStack flow as input and fuse scores at the endLight (flow is separate)RequiredUnsuitable
TSN2DOnly average scores at the endLightUsed (RGB only also possible)Unsuitable
C3D3D3D convolution in every layerHeavyNot neededUnsuitable
I3D3D3D convolution in every layerHeavyUsed (RGB only also possible)Unsuitable
TSM2DShift part of the channels in each residual blockSame as a 2D CNNNot neededPossible with the unidirectional version
SlowFast3D (partly 2D)Two pathways at different frame rates with lateral connectionsModerateNot neededUnsuitable

Rough guidelines for choosing:

  • To capture temporal order at the computational cost of a 2D CNN: TSM is a good fit. It can be inserted into existing 2D CNNs (ResNet or MobileNetV2) without adding parameters.
  • To run in real time on edge devices: The unidirectional TSM is a good fit. In the paper, it took 13.4 ms per frame on a Jetson Nano GPU.
  • When computation is plentiful and the highest accuracy is the goal: On Kinetics, the 3D SlowFast (up to 79.8% on Kinetics-400) achieves higher accuracy than TSM (74.7% with 16 frames). However, evaluation conditions (numbers of clips and crops) differ between papers.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
Example implementation of TSM (Lin, Gan, Han 2019, Sections 3.1-3.3 and 4.1-4.2)
The 2D CNN receives frames stacked along the batch dimension: x is (N*T, C, H, W)
"""


def temporal_shift(x, n_segment, fold_div=8):
  """Bidirectional shift (offline). Shift 1/8 of the channels one frame forward and another 1/8 one frame backward."""
  nt, c, h, w = x.shape
  x = x.view(nt // n_segment, n_segment, c, h, w)   # (N, T, C, H, W)
  fold = c // fold_div
  out = torch.zeros_like(x)                          # fill empty slots with 0
  out[:, :-1, :fold] = x[:, 1:, :fold]               # each step gets the next step's value (from the future)
  out[:, 1:, fold:2 * fold] = x[:, :-1, fold:2 * fold]  # each step gets the previous step's value (from the past)
  out[:, :, 2 * fold:] = x[:, :, 2 * fold:]          # the remaining 3/4 are unchanged
  return out.view(nt, c, h, w)


class ResidualShift(nn.Module):
  """Shift inside the residual branch (Section 3.3). The identity mapping carries the current frame's features unchanged."""

  def __init__(self, branch: nn.Module, n_segment: int):
    super().__init__()
    self.branch = branch          # residual branch (e.g., the convolutions of a ResNet bottleneck)
    self.n_segment = n_segment

  def forward(self, x):
    return x + self.branch(temporal_shift(x, self.n_segment))


class OnlineShift(nn.Module):
  """Unidirectional shift (online, Section 4.2). Remember the first 1/8 of the channels of the previous frame
  and replace the first 1/8 of the current frame with them. Call it one frame at a time with (1, C, H, W)."""

  def __init__(self, fold_div=8):
    super().__init__()
    self.fold_div = fold_div
    self.cache = None

  def forward(self, x):
    fold = x.shape[1] // self.fold_div
    prev = self.cache if self.cache is not None else torch.zeros_like(x[:, :fold])
    self.cache = x[:, :fold].detach().clone()   # keep for the next frame
    return torch.cat([prev, x[:, fold:]], dim=1)


# Usage: process 8 frames with a 2D CNN, with the shift inside the residual branch
T, C = 8, 64
branch = nn.Sequential(nn.Conv2d(C, C, 3, padding=1), nn.BatchNorm2d(C), nn.ReLU())
block = ResidualShift(branch, n_segment=T)
frames = torch.randn(2 * T, C, 56, 56)            # (N*T, C, H, W)
out = block(frames)
print(out.shape)                                   # torch.Size([16, 64, 56, 56])
# Finally, average the per-frame scores over the T frames (same as TSN)
# logits = head(features).view(N, T, -1).mean(dim=1)

FAQ

Q. How can TSM handle temporal information without adding computation?
A.

A convolution can be split into "shifting the input" and "multiplying by weights and summing". TSM performs only the shift along the time axis (no multiplications), and the following 2D convolution computes the multiply-accumulate jointly along the channel dimension. After the shift, the features at each time step contain information from the neighboring time steps, so the 2D convolution acts like a temporal convolution with kernel size 3. Parameters and computation are the same as a 2D CNN.

Q. Why shift only 1/4 of the channels instead of all of them?
A.

Shifting all channels causes two problems. One is that data movement increases and slows things down (13.7% slower on CPU); the other is that the current frame's information is lost, reducing the ability to learn spatial features. In the paper's comparison, shifting 1/4 in total (1/8 in each direction) inside the residual branch gave the highest accuracy, with only about 3% overhead.

Q. How are TSM and TSN related?
A.

TSM is built on TSN. The overall pipeline is the same: frames are sparsely sampled from a video, a 2D CNN produces a score for each frame, and the scores are averaged. The difference is that TSM shifts part of the channels along the time axis inside each residual block, mixing information between frames in the middle of the CNN. In the paper, with matched training and testing conditions, accuracy on Something-Something V1 rose from 20.5% to 47.3%.

References

  1. Lin, J., Gan, C., & Han, S. (2019). TSM: Temporal Shift Module for Efficient Video Understanding. ICCV 2019. arXiv:1811.08383.
  2. mit-han-lab/temporal-shift-module (the authors' released code, ops/temporal_shift.py).
  3. 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.
  4. Feichtenhofer, C., Fan, H., Malik, J., & He, K. (2019). SlowFast Networks for Video Recognition. ICCV 2019. arXiv:1812.03982.