AI Logic

Architectures

MS-TCN

Updated:

MS-TCN architecture. Left: the overall flow (per-frame features go into stage 1; stages 2 to 4 receive only the previous stage's probabilities and refine them; a loss is applied at each stage). Right: inside one stage (SS-TCN): a 1×1 convolution, 10 dilated residual layers with dilation doubling from 1 to 512, and a 1×1 convolution with softmax

Background and overview

MS-TCN (Multi-Stage Temporal Convolutional Network) is a model that assigns an action label to every frame of a video by stacking several temporal convolutional networks built only from dilated convolutions (SS-TCN), with each stage refining the predictions of the previous one. It was presented at CVPR 2019 by Abu Farha and Gall of the University of Bonn.

The task it addresses is action segmentation. In a video several minutes long, such as a cooking video, the goal is to identify which action, such as "cut" or "mix", each frame belongs to.

The earlier TCN (Lea et al. 2017) captured long-range temporal relations with temporal pooling. The paper points out that pooling risks losing fine-grained motion information, and that prior work downsampled videos to 1–3 frames per second. MS-TCN answers this in two ways.

  • Process time without downsampling: Instead of pooling, it enlarges the receptive field with dilated convolutions and computes at the full 15 frames per second.
  • Refine predictions stage by stage: The previous stage's predictions (class probabilities) are passed to the next stage, reducing errors where segments are chopped into small pieces (over-segmentation). Training also adds a smoothing loss that penalizes abrupt changes in prediction between adjacent frames.

The main results of the paper are as follows.

  • On three datasets, 50Salads, GTEA, and Breakfast, it achieved the best results at the time on all of segmental F1@k, Edit score, and frame-wise accuracy.
  • On 50Salads, F1@10 rose from 27.0 with a single stage (SS-TCN) to 76.3 with four stages. Frame-wise accuracy was around 80% in both cases; the benefit of stacking stages appeared mainly as reduced over-segmentation.

Theory: stacking single-stage TCNs to refine predictions

MS-TCN takes the per-frame features x1:Tx_{1:T} of a video and outputs the class c1:Tc_{1:T} of each frame (TT is the video length). The whole model stacks four single-stage models (SS-TCN) of the same form (figure at the top of this article).

The single-stage model (SS-TCN)

A single stage consists only of the following layers (right side of the figure at the top of this article). It uses no pooling, which would reduce the number of time steps, and no fully connected layers, which would fix the input length.

  1. 1×1 convolution: Maps the input feature dimension to the network's channel count DD (64 in the paper).
  2. 10 dilated residual layers: Each layer applies a dilated convolution with kernel size 3, ReLU, and a 1×1 convolution, and adds the result to the layer input (residual connection). The dilation doubles at each layer: 1, 2, 4, …, 512. Unlike WaveNet, the convolution is non-causal and also looks at future frames.
  3. Output: A 1×1 convolution maps to the number of classes CC, and a softmax gives the class probabilities for each frame.

Layer ll computes the following (∗* is convolution, W1W_1 the dilated convolution weights, and W2W_2 the 1×1 convolution weights).

H^l=ReLU(W1∗Hl−1+b1),Hl=Hl−1+W2∗H^l+b2\hat{H}_l = \mathrm{ReLU}(W_1 * H_{l-1} + b_1), \qquad H_l = H_{l-1} + W_2 * \hat{H}_l + b_2

With kernel size 3, the receptive field up to layer ll is as follows, doubling with each added layer.

ReceptiveField(l)=2l+1−1\mathrm{ReceptiveField}(l) = 2^{l+1} - 1

With 10 layers this is 2047 frames, or about 136 seconds at 15 frames per second. Because the receptive field grows exponentially just by adding layers, the model can see long time spans without adding parameters, which the paper says also helps prevent overfitting to the training data.

Stacking stages (Multi-Stage)

The first stage takes the features, and from the second stage on, each stage receives only the per-frame probabilities produced by the previous stage.

Y0=x1:T,Ys=F(Ys−1)Y^0 = x_{1:T}, \qquad Y^s = \mathcal{F}(Y^{s-1})

F\mathcal{F} is the single-stage model and YsY^s is the output of stage ss. This brings the idea of stacking predictions over multiple stages, used in human pose estimation, to action segmentation.

Loss function

The loss of each stage is the sum of a classification loss and a smoothing loss.

  1. Classification loss: Frame-wise cross-entropy. yt,cy_{t,c} is the predicted probability of class cc at time tt.
  2. Smoothing loss (T-MSE): The difference Δt,c\Delta_{t,c} between the log probabilities of adjacent frames is capped at τ\tau, and the mean of the squares is taken (a truncated mean squared error).
  3. Total: The per-stage losses Ls\mathcal{L}_s are summed over all stages.
Lcls=1T∑t−log⁡yt,c,LT-MSE=1TC∑t,cΔ~t,c2\mathcal{L}_{cls} = \frac{1}{T} \sum_t -\log y_{t,c}, \qquad \mathcal{L}_{T\text{-}MSE} = \frac{1}{TC} \sum_{t,c} \tilde{\Delta}_{t,c}^2 Δ~t,c=min⁡(Δt,c,τ),Δt,c=∣log⁡yt,c−log⁡yt−1,c∣\tilde{\Delta}_{t,c} = \min(\Delta_{t,c}, \tau), \qquad \Delta_{t,c} = \left| \log y_{t,c} - \log y_{t-1,c} \right| Ls=Lcls+λLT-MSE,L=∑sLs\mathcal{L}_s = \mathcal{L}_{cls} + \lambda \mathcal{L}_{T\text{-}MSE}, \qquad \mathcal{L} = \sum_s \mathcal{L}_s

Gradients are computed only with respect to yt,cy_{t,c}; the previous frame's yt−1,cy_{t-1,c} is treated as a constant. The paper uses τ=4\tau = 4 and λ=0.15\lambda = 0.15.

Training settings (Section 3.4 of the paper)

  • 4 stages, 10 dilated residual layers per stage, 64 filters in every layer, kernel size 3
  • Dropout after each layer
  • Adam, learning rate 0.0005
  • Input: I3D features (not fine-tuned), 15 frames per second

Why over-segmentation decreases

The paper explains why MS-TCN reduces over-segmentation in terms of three design choices.

1. Pass only probabilities to the next stage

From the second stage on, a stage sees only the previous stage's predictions (the probability of each action). The next stage therefore refines the predictions using only the sequence of labels, that is, which actions the surrounding frames are predicted to be. For example, if a single frame of "add" appears in the middle of a run of "mix", the context lets it be corrected to "mix".

The paper also tried passing the features of the previous stage's last layer along with the probabilities, and reports that F1 and Edit score dropped by about 20 points. Since many actions look and move alike, the authors believe passing features confuses the next stage too, leading it to output short erroneous segments.

As an everyday analogy, the second and later stages are "proofreaders who correct a draft by reading only the draft". They fix only places where the flow of sentences (the label sequence) is off, without looking at the source material (the features), so they are not misled by its ambiguities.

2. Stacking stages differs from simply going deeper

Stacking stages also adds parameters. The paper compares a 4-stage MS-TCN with an SS-TCN of the same number of layers (48) and shows that MS-TCN is more than 27 points higher in F1@10. Applying a loss at each stage and making each stage output predictions is what makes the difference.

3. The smoothing loss

T-MSE penalizes abrupt changes in predicted probabilities between adjacent frames. Because the difference is capped at τ\tau, however, it does not strongly penalize a sharp probability switch at a true action boundary. Comparing it with a loss based on KL divergence, the paper explains that KL barely penalizes cases where the difference between prediction and target is very small, whereas T-MSE penalizes small differences too and is symmetric.

Even a single-stage SS-TCN has nearly the same frame-wise accuracy as MS-TCN (78.2% vs. 80.7% on 50Salads). The difference shows up in F1@k and Edit score. MS-TCN's design choices aim to improve how segments hold together rather than frame-by-frame hits and misses.

Experimental results

The paper evaluates on 50Salads (50 videos of salad preparation, 17 classes, 6.4 minutes on average), GTEA (28 kitchen videos from a head-mounted camera, 11 classes including background), and Breakfast (1,712 videos of breakfast preparation filmed in 18 kitchens, 48 classes).

Effect of the number of stages (50Salads; Table 1 of the paper)

ModelF1@{10, 25, 50}EditFrame-wise accuracy (%)
SS-TCN (1 stage)27.0, 25.3, 21.520.578.2
MS-TCN (2 stages)55.5, 52.9, 47.347.979.8
MS-TCN (3 stages)71.5, 68.6, 61.164.078.6
MS-TCN (4 stages)76.3, 74.0, 64.567.980.7
MS-TCN (5 stages)76.4, 73.4, 63.669.279.5

Performance improves greatly at 2–3 stages and a little more at 4. At 5 stages some metrics begin to drop, which the paper attributes to possible overfitting from the added parameters. Subsequent experiments use 4 stages.

Compared with a single stage of the same depth (50Salads; Table 2 of the paper)

ModelF1@{10, 25, 50}EditFrame-wise accuracy (%)
SS-TCN (48 layers)49.0, 46.4, 40.240.778.0
MS-TCN (4 stages × 12 layers)76.3, 74.0, 64.567.980.7

Comparison of loss functions (50Salads; Table 3 of the paper)

LossF1@{10, 25, 50}EditFrame-wise accuracy (%)
Cross-entropy only71.3, 69.7, 60.764.279.9
+ KL divergence71.9, 69.3, 60.164.680.2
+ T-MSE76.3, 74.0, 64.567.980.7

Comparison with prior work (Table 10 of the paper)

DatasetModelF1@{10, 25, 50}EditFrame-wise accuracy (%)
50SaladsED-TCN68.0, 63.9, 52.659.864.7
50SaladsTDRN72.9, 68.5, 57.266.068.1
50SaladsMS-TCN76.3, 74.0, 64.567.980.7
GTEAED-TCN72.2, 69.3, 56.0―64.0
GTEATDRN79.2, 74.4, 62.774.170.1
GTEAMS-TCN85.8, 83.4, 69.879.076.3
GTEAMS-TCN (fine-tuned features)87.5, 85.4, 74.681.479.2
BreakfastGRU (prior work)――60.6
BreakfastMS-TCN (I3D)52.6, 48.1, 37.961.766.3
BreakfastMS-TCN (IDT)58.2, 52.9, 40.861.465.1

The prior-work numbers come from each paper's own features and settings, so the input features are not matched (MS-TCN uses I3D). On Breakfast, IDT features, which represent motion only, gave higher F1. The paper attributes this to breakfast videos all looking similar, so that appearance information is not a useful cue for the action.

Other analyses (50Salads and GTEA)

  • Temporal resolution (Table 6): Downsampling to 1 frame per second slightly raised F1@10 to 77.8 and Edit to 70.7, but lowered frame-wise accuracy to 78.6% (80.7% at 15 frames per second). Downsampling makes over-segmentation less likely but loses precise boundary positions and short segments.
  • Number of layers per stage (Table 7): Going from 6 to 10 layers widened the receptive field and improved results greatly (F1@10 from 53.2 to 76.3). With 12 layers, frame-wise accuracy was unchanged and F1 rose slightly.
  • Video length (Table 8, GTEA): Videos longer than 1.5 minutes scored somewhat lower than those under 1 minute (F1@50 from 77.0 to 58.4). The paper attributes this to the limited receptive field.
  • Training speed: The paper reports that training a 4-stage MS-TCN for 50 epochs on 50Salads was 4 times faster than training a single Bi-LSTM with a 64-dimensional hidden state.

Practical considerations

Keep the following points in mind when using MS-TCN.

  • Prepare the features in advance: MS-TCN takes per-frame features computed beforehand, for example with I3D. The paper uses the features without fine-tuning; fine-tuning on GTEA raised F1@10 from 85.8 to 87.5. Results depend on which features are used.
  • The receptive field stops at about 2,000 frames: The receptive field of 10 layers is 2047 frames (about 136 seconds at 15 frames per second). Relations over longer spans are not seen directly, and in the paper performance dropped slightly on long videos.
  • It uses future frames: The dilated convolutions are non-causal, looking at frames on both sides. The model suits uses where the whole video is available before segmenting, and cannot be used as is for on-the-fly decisions.
  • Check the dropout rate in the released code: The paper only says that dropout is used after each layer. The authors' released code places PyTorch's nn.Dropout() with its default rate (0.5) after the 1×1 convolution, before the residual is added.

A smoothing loss that is too strong erases true boundaries as well. In the paper, raising τ\tau from 4 to 5 dropped F1@10 on 50Salads sharply from 76.3 to 66.6, and frame-wise accuracy from 80.7% to 74.0%. A large τ\tau penalizes even cases where the model clearly judges adjacent frames to be different actions. Raising λ\lambda from 0.15 to 0.25 also lowered frame-wise accuracy to 78.9%. When moving to new data, check τ\tau and λ\lambda on validation data.

Comparison with other models

Comparing action segmentation models from the same angles gives the following.

ModelTemporal resolutionHow the receptive field is enlargedMeasures against over-segmentationComputation
ED-TCNDownsampled to 1–3 frames/sLong filters + poolingCoarse view through long filtersAll time steps in parallel
TDRNDownsampled to 1–3 frames/sEncoder-decoder + deformable convolutionAdds a residual streamAll time steps in parallel
SS-TCN (1 stage)Kept at 15 frames/sDilation doubled per layerNone (much over-segmentation)All time steps in parallel
MS-TCNKept at 15 frames/sDilation doubled per layerStacked stages refine predictions + smoothing lossAll time steps in parallel
Bi-LSTM (bidirectional RNN)―The whole sequence in principleNoneComputed step by step in time order

The main difference from ED-TCN is how the number of time steps is handled. ED-TCN reduces the number of time steps with pooling to see long spans, whereas MS-TCN keeps the number of time steps and sees long spans with dilated convolutions. This makes it easier to preserve fine boundaries, and on 50Salads frame-wise accuracy rose from 64.7% to 80.7% (note that the features also differ).

A rough guide to choosing:

  • You want a baseline for supervised action segmentation: MS-TCN is a good starting point. The authors' PyTorch code is publicly available.
  • You need precise boundary positions: MS-TCN, which processes time without downsampling, is well suited.
  • Over-segmentation is still frequent: Increase the number of stages (up to about 4), or tune the smoothing loss's λ\lambda and τ\tau on validation data.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
Example implementation of MS-TCN (Abu Farha & Gall 2019, Sections 3.1-3.4)
Input: per-frame features (N, D_in, T)  Output: class scores of each stage (num_stages, N, C, T)
"""


class DilatedResidualLayer(nn.Module):
  def __init__(self, dilation, ch, dropout=0.5):
    super().__init__()
    # kernel 3, padding = dilation keeps the number of time steps T (non-causal: looks at frames on both sides)
    self.conv_dilated = nn.Conv1d(ch, ch, 3, padding=dilation, dilation=dilation)
    self.conv_1x1 = nn.Conv1d(ch, ch, 1)
    self.dropout = nn.Dropout(dropout)   # the rate is not given in the paper; the released code uses the default 0.5

  def forward(self, x):
    out = F.relu(self.conv_dilated(x))   # Eq. 1
    out = self.dropout(self.conv_1x1(out))
    return x + out                       # Eq. 2: add the layer input


class SingleStageTCN(nn.Module):
  def __init__(self, in_dim, num_classes, ch=64, num_layers=10):
    super().__init__()
    self.conv_in = nn.Conv1d(in_dim, ch, 1)                       # map the dimension to 64
    self.layers = nn.ModuleList([DilatedResidualLayer(2 ** i, ch) for i in range(num_layers)])  # dilation 1, 2, ..., 512
    self.conv_out = nn.Conv1d(ch, num_classes, 1)                 # map to the number of classes

  def forward(self, x):
    x = self.conv_in(x)
    for layer in self.layers:
      x = layer(x)
    return self.conv_out(x)              # scores before softmax


class MSTCN(nn.Module):
  def __init__(self, in_dim, num_classes, num_stages=4):
    super().__init__()
    self.stage1 = SingleStageTCN(in_dim, num_classes)
    # from stage 2 on, only the previous stage's probabilities (C dimensions) are received
    self.stages = nn.ModuleList([SingleStageTCN(num_classes, num_classes) for _ in range(num_stages - 1)])

  def forward(self, x):
    out = self.stage1(x)
    outputs = [out]
    for stage in self.stages:
      out = stage(F.softmax(out, dim=1))
      outputs.append(out)
    return torch.stack(outputs)          # (num_stages, N, C, T)


def ms_tcn_loss(outputs, labels, lam=0.15, tau=4.0):
  """Sum over all stages of cross-entropy + λ × truncated MSE (Eqs. 7-13)"""
  loss = 0.0
  for p in outputs:                                       # p: (N, C, T)
    loss = loss + F.cross_entropy(p, labels)
    logp = F.log_softmax(p, dim=1)
    prev = F.log_softmax(p.detach(), dim=1)[:, :, :-1]    # treat the previous frame as a constant
    delta = (logp[:, :, 1:] - prev).abs().clamp(max=tau)  # cap |log y_t - log y_{t-1}| at τ
    loss = loss + lam * (delta ** 2).mean()
  return loss


model = MSTCN(in_dim=2048, num_classes=17)               # I3D features are 2048-dimensional
feats = torch.randn(1, 2048, 3000)                       # one video, 3000 frames (200 seconds at 15 frames/s)
labels = torch.randint(0, 17, (1, 3000))

model.train()                                            # training: dropout is active
optimizer = torch.optim.Adam(model.parameters(), lr=0.0005)
loss = ms_tcn_loss(model(feats), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                             # inference: dropout does nothing
with torch.no_grad():
  pred = model(feats)[-1].argmax(dim=1)                  # use the last stage's prediction: (1, 3000)

FAQ

Q. How does MS-TCN differ from TCN (ED-TCN)?
A.

ED-TCN is an encoder-decoder that reduces the number of time steps with pooling and then restores it, and it used videos downsampled to a few frames per second. MS-TCN uses no pooling, enlarges the receptive field with dilated convolutions, and computes at the full 15 frames per second. It also reduces errors where segments are chopped into small pieces by stacking four single-stage models that refine the previous stage's predictions and by adding a smoothing loss.

Q. Why pass only probabilities, not features, to the next stage?
A.

In the paper's experiments, passing the previous stage's features as well lowered F1 and Edit score on 50Salads by about 20 points. The paper believes that because actions often look and move alike, passing features confuses the next stage too, leading it to output short erroneous segments. Passing only probabilities makes the next stage focus on the label sequence of the surrounding frames when refining.

Q. What do $\tau$ and $\lambda$ in the smoothing loss control?
A.

λ\lambda is the weight of the smoothing loss, and τ\tau is where the difference in log probabilities between adjacent frames is capped. The paper uses τ=4\tau = 4 and λ=0.15\lambda = 0.15. Raising τ\tau to 5 penalizes even true boundaries where the model clearly judges adjacent frames to be different actions, and F1@10 on 50Salads dropped from 76.3 to 66.6. Too strong a setting erases boundaries, so choose the values by checking on validation data.

References

  1. Abu Farha, Y., & Gall, J. (2019). MS-TCN: Multi-Stage Temporal Convolutional Network for Action Segmentation. CVPR 2019. arXiv:1903.01945.
  2. yabufarha/ms-tcn (authors' released code, model.py).
  3. Lea, C., Flynn, M. D., Vidal, R., Reiter, A., & Hager, G. D. (2017). Temporal Convolutional Networks for Action Segmentation and Detection. CVPR 2017. arXiv:1611.05267.
  4. van den Oord, A., Dieleman, S., Zen, H., et al. (2016). WaveNet: A Generative Model for Raw Audio. arXiv:1609.03499.