AI Logic

Architectures

TCN

Updated:

Two forms of TCN. Left: ED-TCN (an encoder that reduces the number of time steps to a quarter with temporal convolutions and max pooling, a decoder that restores it with upsampling and convolutions, and a per-frame fully connected layer with softmax). Right: Dilated TCN (B stacked blocks, each grouping L layers of dilated convolution, weights V, and a residual connection; the block outputs are summed and passed through ReLU, weights V_r, and a fully connected layer with softmax)

Background and overview

A TCN (Temporal Convolutional Network) is a model that takes per-frame video features as input, stacks temporal convolutions hierarchically, and assigns an action label to every frame. Lea et al. proposed it in a 2016 workshop paper, and their CVPR 2017 paper organized it into two forms: the encoder-decoder ED-TCN and the Dilated TCN, an adaptation of WaveNet.

The task covered in this article is action segmentation. In a cooking video, for example, the goal is to determine frame by frame which action ("cut → add → mix") occupies which span of a video several minutes long.

Earlier methods usually split the problem into two stages:

  1. For each frame, compute short-term features with an image CNN or a similar model
  2. Apply an RNN such as an LSTM, or a CRF, to the feature sequence to capture long-range temporal relations

The paper points out weaknesses in each second-stage approach: sliding-window detectors struggle to capture long-range temporal relations, and RNNs are hard to interpret and hard to train. TCN replaces the second stage with convolutions only and computes all time steps at once.

The paper's main results are:

  • ED-TCN achieved state-of-the-art results at the time on three datasets: 50Salads, GTEA, and MERL Shopping.
  • Compared with a bidirectional RNN (Bi-LSTM) on the same input, it scored higher on segment-level metrics and trained about 30 times faster (about 1 minute versus about 30 minutes for 200 epochs on one 50Salads split).
  • To measure errors where segments are chopped into small pieces (over-segmentation), it proposed the segmental F1@k.

The name "TCN" is also used by Bai et al. (2018) for a general-purpose convolutional network for sequence modeling (their public code is also called TCN). This article covers the TCN of Lea et al. for action segmentation.

Theory: ED-TCN and Dilated TCN

Both TCNs take a sequence of per-frame features Xt∈RF0X_t \in \mathbb{R}^{F_0} (1≤t≤T1 \le t \le T) as input and output per-frame class probabilities Y^t∈[0,1]C\hat{Y}_t \in [0, 1]^C (CC is the number of classes). The paper lists three properties shared by both:

  • Layer-wise computation: Instead of updating one frame at a time as an RNN does, all time steps of a layer are computed simultaneously.
  • Temporal convolution: 1D convolutions are applied along the time axis.
  • Fixed receptive field: Each frame's prediction depends only on inputs within a fixed time span (the receptive field).

ED-TCN (encoder-decoder)

ED-TCN halves the temporal length repeatedly and then restores it (left of the figure at the top of the article). The paper notes that this design resembles encoder-decoder models for semantic image segmentation (SegNet).

  1. Encoder: Each layer applies a temporal convolution of length dd, an activation function ff, and max pooling of width 2. Pooling reduces the number of time steps to Tl=Tl−1/2T_l = T_{l-1}/2.
  2. Decoder: Each layer applies upsampling (repeating each value twice), a convolution of length dd, and ff, in that order, restoring the number of time steps. The filter counts follow the encoder in reverse order.
  3. Output: The output of the last decoder layer, Dt(1)D^{(1)}_t, is turned into class probabilities with a fully connected layer and softmax.

The computation of encoder layer ll is as follows (∗* is temporal convolution):

E(l)=f(W∗E(l−1)+b),Y^t=softmax(UDt(1)+c)E^{(l)} = f\left(W * E^{(l-1)} + b\right), \qquad \hat{Y}_t = \mathrm{softmax}\left(U D^{(1)}_t + c\right)

Layer ll has Fl=96+32lF_l = 96 + 32l filters, i.e., 128 and 160 for two layers. The activation function is a normalized ReLU that divides by the maximum value at each frame (ϵ=10−5\epsilon = 10^{-5}):

f(x)=ReLU(x)max⁡ReLU(x)+ϵf(x) = \frac{\mathrm{ReLU}(x)}{\max \mathrm{ReLU}(x) + \epsilon}

The paper reports that it also tried skip connections across layers and other normalizations, but this simple form worked better.

Dilated TCN (WaveNet-style)

Dilated TCN adapts WaveNet, a model for audio generation, to action segmentation (right of the figure at the top of the article). It uses no pooling or upsampling; it keeps the number of time steps at TT and stacks dilated convolutions deeply.

  1. BB blocks, each containing LL layers, are chained. Every layer has the same number of filters FwF_w (128 in the paper).
  2. Each layer is a convolution with dilation rate ss that uses only the values at two time steps, t−st - s and tt. The dilation rate doubles with each layer within a block (sl=2ls_l = 2^l).
  3. The convolution output is transformed by weights VV and added to the layer input (residual connection).
  4. The outputs of the BB blocks are summed and passed through ReLU (skip connections), transformed by weights VrV_r followed by ReLU, and turned into class probabilities with a fully connected layer and softmax.

The computation of layer ll in block jj is as follows:

S^t(j,l)=f(W(1)St−s(j,l−1)+W(2)St(j,l−1)+b),St(j,l)=St(j,l−1)+VS^t(j,l)+e\hat{S}^{(j,l)}_t = f\left(W^{(1)} S^{(j,l-1)}_{t-s} + W^{(2)} S^{(j,l-1)}_t + b\right), \qquad S^{(j,l)}_t = S^{(j,l-1)}_t + V \hat{S}^{(j,l)}_t + e

Receptive field size

According to the paper, the time span used for each frame's prediction (the receptive field) is:

ModelReceptive fieldHow to enlarge it
ED-TCNr(d,L)=d(2L−1)+1r(d, L) = d(2^L - 1) + 1Longer filters (dd), more layers (LL)
Dilated TCNr(B,L)=B⋅2Lr(B, L) = B \cdot 2^LMore blocks (BB), more layers per block (LL)

ED-TCN has few layers (e.g., 3 in the encoder) with long filters, whereas Dilated TCN has many layers, each with filters spanning only 2 time steps.

Causal and acausal

The paper tests two settings depending on whether future frames are used:

  • Causal: The prediction at time tt uses only inputs from 11 to tt. This is required for on-the-fly decisions such as in robotics. ED-TCN convolves over Xt−dX_{t-d} to XtX_t.
  • Acausal: Any past or future time step can be used. ED-TCN convolves over Xt−d/2X_{t - d/2} to Xt+d/2X_{t + d/2}, and each Dilated TCN layer uses the three time steps t−st - s, tt, and t+st + s.

Training

The loss is per-frame cross-entropy, optimized with Adam. Dropout is applied not to individual weights but to entire filters (channels), in the form of Spatial Dropout; the paper reports that this improved performance and produced smoother weights.

Why it captures long sequences of actions

The paper uses experiments on synthetic data to confirm that TCNs capture, with convolutions alone, the properties that RNNs and segmental models (such as CRFs) captured (the receptive field is 16 frames for both TCNs).

  • Action compositions: Sequences were built in which "A always proceeds A1 → A2 → A3, followed by B or C", with identical input features for A1 to A3. A classifier that looks at a single frame cannot tell them apart, but the TCNs used their long receptive fields to look at the surrounding context and segmented every frame correctly. They also got everything right in a setting where segment lengths differed by class, so the paper concludes that they can capture segment durations as well.
  • Long-range temporal dependencies: The input features were shifted by ss frames relative to the ground-truth labels. This corresponds to a cooking scene where a tomato is cut while hidden by the hand, and the model must remember that the tomato was on the cutting board before cutting began.
Models = 0s = 5s = 10s = 15s = 20
ED-TCN10097.989.574.157.1
Dilated TCN10092.787.069.661.5
Bi-LSTM10072.360.254.738.5

(F1@10. Table 1 of the paper.) Both TCNs performed well for shifts up to about half the receptive field, whereas Bi-LSTM degraded quickly as the shift grew.

Why over-segmentation is low

On real data, ED-TCN, Dilated TCN, and ST-CNN (prior work) had similar frame-wise accuracy, but their segmental F1@k and Edit score differed greatly. The paper attributes the gap to filter length.

  • ED-TCN: With few layers and long filters, a single filter sees a long span of time at once. Predictions are less likely to flip back and forth mid-segment, so over-segmentation is low.
  • Dilated TCN: Each layer's filter spans only 2 time steps, so even with high frame-wise accuracy, it is prone to over-segmentation.

As an everyday analogy, ED-TCN is like "skimming a video in fast-forward to get the big picture, then returning to normal speed to settle the details." Because it decides "this span is mixing" as a whole during the fast-forward stage, it is less likely to be thrown off by a single misread frame in the middle.

Why training is fast

Time steps within a layer do not depend on each other, so all of them can be computed together on a GPU. An RNN needs the result at t−1t - 1 to compute time step tt within a layer, so it must compute sequentially.

Experimental results

The paper compares models using action segmentation metrics (frame-wise accuracy, Edit score) and an action detection metric (mAP), plus its proposed F1@k (kk = 10, 25, 50). The results for 50Salads and GTEA are in the acausal setting, which also uses future frames.

50Salads (Table 2 of the paper. 50 videos of salad preparation, 5–10 minutes each. Downsampled to about 1 frame/s, 5-fold cross-validation.)

Model (high-level granularity, 9 classes + background)F1@{10, 25, 50}EditFrame-wise accuracy (%)
Spatial CNN35.0, 30.5, 22.725.568.0
Dilated TCN55.8, 52.3, 44.346.971.1
ST-CNN61.7, 57.3, 47.252.871.3
Bi-LSTM72.2, 68.4, 57.867.770.9
ED-TCN76.5, 73.8, 64.572.273.4
Model (mid-level granularity, 17 classes)F1@{10, 25, 50}EditFrame-wise accuracy (%)
Spatial CNN32.3, 27.1, 18.924.854.9
IDT+LM44.4, 38.9, 27.845.848.7
Dilated TCN52.2, 47.6, 37.443.159.3
ST-CNN55.9, 49.6, 37.145.959.4
Bi-LSTM62.6, 58.3, 47.055.655.7
ED-TCN68.0, 63.9, 52.659.864.7

ED-TCN gave the best results on every metric at both granularities. At the mid level, it also beat IDT+LM on IoU-based mAP (IDT+LM: mAP@10 of 37.9 and mAP@50 of 22.9; ED-TCN: 64.9 and 42.3).

GTEA (Table 4 of the paper. 28 kitchen videos recorded with a head-mounted camera, 11 classes. Leave-one-subject-out evaluation.)

ModelF1@{10, 25, 50}Frame-wise accuracy (%)
EgoNet+TDD―64.4
ST-CNN58.7, 54.4, 41.960.6
Dilated TCN58.8, 52.2, 42.258.3
Bi-LSTM66.5, 59.0, 43.655.5
ED-TCN72.2, 69.3, 56.064.0

Frame-wise accuracy was on par with EgoNet+TDD, which uses no temporal model. The paper adds that ED-TCN's inputs are simple image CNN features that can be computed in real time.

MERL Shopping (Table 3 of the paper. 106 surveillance videos in front of store shelves, 5 classes + background.)

SettingModelF1@{10, 25, 50}mAP@midFrame-wise accuracy (%)
AcausalMSN Seg (Bi-LSTM)80.0, 78.3, 65.469.876.3
AcausalDilated TCN79.9, 78.0, 67.575.676.4
AcausalED-TCN86.7, 85.1, 72.974.479.0
CausalDilated TCN72.7, 70.6, 56.572.273.0
CausalED-TCN82.1, 79.8, 64.064.274.1

The acausal setting was clearly better than the causal one; the paper states that using future information matters for performance. Because Dilated TCN scored higher on mAP@mid (a hit if the segment midpoint falls within a ground-truth segment), the paper suggests that Dilated TCN's prediction confidences are more reliable.

Activation function comparison (Table 5 of the paper. 50Salads mid-level granularity, F1@25.)

ActivationSigmoidReLUTanhGPCNormalized ReLU
ED-TCN37.340.448.152.758.4
Dilated TCN42.543.141.040.540.7

For ED-TCN, normalized ReLU was best; for Dilated TCN, all functions performed similarly. GPC is the tanh⁡(x)⊙sigmoid(x)\tanh(x) \odot \mathrm{sigmoid}(x) form used in WaveNet. This table was trained with different hyperparameters, so its values do not match those in the tables above.

Receptive field (Figure 4 of the paper. 50Salads mid-level granularity.)

ED-TCN performed best with L=2L = 2 and d=15d = 15 (about 52 seconds), and Dilated TCN performed best with B=4B = 4 and L=5L = 5 (128 frames) (nearly the same with B=3B = 3, L=5L = 5, i.e., 96 frames).

Practical considerations

Keep the following in mind when using a TCN:

  • Prepare per-frame features separately: A TCN takes a sequence of features computed beforehand by an image CNN or a similar model. In the paper, a small VGG-like CNN was trained for each dataset, or features from prior work were reduced to 50 dimensions with principal component analysis. Feature quality strongly affects the results.
  • Match the receptive field to action durations: A short receptive field cannot use the context of long actions, while an overly long one increases computation and memory. In the paper's environment, ED-TCN ran out of memory beyond L=4L = 4 and d=25d = 25. Downsampling frames (about 1 frame/s for 50Salads) lets the same receptive field cover a longer time span.
  • Pad ED-TCN inputs to a multiple of 2L2^L: Because the length is halved by pooling and then doubled back, the 2016 paper says to pad sequences so that their length is divisible by 2L2^L. The implementation example below also pads the input and crops it at the end.
  • Choose causal or acausal based on the use case: For on-the-fly decisions, the causal setting that does not look at the future is required, and performance drops (F1@50 on MERL Shopping: 72.9 → 64.0).

Comparing by frame-wise accuracy alone hides how much over-segmentation there is. In the paper, ED-TCN, Dilated TCN, and ST-CNN had nearly the same frame-wise accuracy (64.7, 59.3, and 59.4 at the 50Salads mid level), yet their F1@k and Edit scores differed greatly. Action segmentation models should report F1@{10, 25, 50}, Edit score, and frame-wise accuracy together.

Comparison with other models

Comparing action segmentation models from the same perspectives gives the following:

ModelTemporal processingHow the receptive field growsOver-segmentationComputation
ED-TCNLong convolutions + pooling/upsamplingFilter length dd and number of layersLowAll time steps in parallel
Dilated TCNDeep stack of 2-step dilated convolutionsNumber of blocks and layers (dilation doubles each layer)HigherAll time steps in parallel
Bi-LSTM (bidirectional RNN)Updates state one step at a time from both directionsIn principle, the whole sequenceModerateSequential over time (about 30× longer training in the paper)
MS-TCNStacks several dilated-convolution TCN stages, each refining the previous stage's predictionsDilation doubles each layer; number of time steps keptDecreases with more stagesAll time steps in parallel
WaveNetCausal dilated convolutionsDilation doubles each layer―A model for audio generation

The difference between ED-TCN and Dilated TCN is "few layers with long filters" versus "many layers with short filters." In the paper's experiments, ED-TCN had better F1@k and Edit scores, while Dilated TCN had more reliable segment confidences (higher mAP@mid).

Rough guidelines for choosing:

  • Getting segment boundaries and orderings right (action segmentation): ED-TCN is the baseline. In later work, MS-TCN, which stacks several stages of dilated convolutions while keeping the number of time steps, became the widely used reference model for this task.
  • Detection that relies on per-prediction confidence: Dilated TCN had higher mAP@mid in the paper and is a candidate.
  • On-the-fly decisions are required: Use the causal setting. Performance drops because the future is not used.

PyTorch example

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

"""
A small implementation of ED-TCN (Lea et al. 2017, Sections 3.1 and 3.3)
Input: per-frame features (N, F0, T)  Output: per-frame class scores (N, C, T)
"""


class NormReLU(nn.Module):
  """Normalized ReLU: divide by the channel-wise maximum at each frame (Eq. 8)"""
  def __init__(self, eps=1e-5):
    super().__init__()
    self.eps = eps

  def forward(self, x):                      # x: (N, F, T)
    x = F.relu(x)
    return x / (x.amax(dim=1, keepdim=True) + self.eps)


class EDTCN(nn.Module):
  def __init__(self, in_dim, num_classes, num_layers=2, kernel=15, dropout=0.3):
    super().__init__()
    # The paper does not state the dropout rate, so 0.3 is used here as an example
    chans = [96 + 32 * l for l in range(1, num_layers + 1)]   # F_l = 96 + 32 l (128, 160 for 2 layers)
    pad = kernel // 2                                          # Acausal: convolve from t - d/2 to t + d/2
    self.L = num_layers

    self.enc = nn.ModuleList()
    prev = in_dim
    for c in chans:
      self.enc.append(nn.Sequential(
        nn.Dropout1d(dropout),                    # Drop entire filters (channels) (Spatial Dropout)
        nn.Conv1d(prev, c, kernel, padding=pad),  # Temporal convolution (length d)
        NormReLU(),
        nn.MaxPool1d(2),                          # Halve the number of time steps
      ))
      prev = c

    self.dec = nn.ModuleList()
    for c in reversed(chans):                     # Filter counts in reverse order of the encoder
      self.dec.append(nn.Sequential(
        nn.Upsample(scale_factor=2, mode="nearest"),  # Repeat each value twice
        nn.Dropout1d(dropout),
        nn.Conv1d(prev, c, kernel, padding=pad),
        NormReLU(),
      ))
      prev = c

    self.out = nn.Conv1d(prev, num_classes, 1)    # Same fully connected layer for every frame (1×1 convolution)

  def forward(self, x):                           # x: (N, F0, T)
    T = x.shape[-1]
    unit = 2 ** self.L
    x = F.pad(x, (0, (-T) % unit))                # Pad the length to a multiple of 2^L
    for layer in self.enc:
      x = layer(x)
    for layer in self.dec:
      x = layer(x)
    return self.out(x)[..., :T]                   # Crop the padding. Softmax is computed inside the loss


model = EDTCN(in_dim=128, num_classes=10)
feats = torch.randn(2, 128, 300)                  # 2 videos, 128-dim features, 300 frames
labels = torch.randint(0, 10, (2, 300))          # Ground-truth class for each frame

model.train()                                     # Training: Dropout1d is active
logits = model(feats)                             # (2, 10, 300)
loss = F.cross_entropy(logits, labels)            # Per-frame cross-entropy
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                      # Inference: Dropout1d does nothing
with torch.no_grad():
  pred = model(feats).argmax(dim=1)               # (2, 300) action class for each frame

FAQ

Q. How does a TCN differ from an RNN (LSTM)?
A.

An RNN updates the state at time tt from the state at t−1t - 1, so it can only compute in time order. A TCN computes all time steps of a layer simultaneously with temporal convolutions, so they can be computed together on a GPU. In the paper, training on one 50Salads split for 200 epochs took about 1 minute for ED-TCN and about 30 minutes for Bi-LSTM. Another difference is that the time span used for each frame's prediction (the receptive field) is determined by the filter length and the number of layers.

Q. Should I use ED-TCN or Dilated TCN?
A.

In the paper's experiments, ED-TCN was better on almost all action segmentation metrics (F1@k, Edit score, frame-wise accuracy). Because ED-TCN sees a long span of time at once with long filters, it makes fewer errors where segments are chopped into small pieces. On the other hand, Dilated TCN scored higher on mAP, which judges hits by segment midpoints, so it is a candidate for detection that uses prediction confidences.

Q. How are the input features for a TCN created?
A.

A TCN takes a sequence of per-frame features. In the paper, features for 50Salads and GTEA came from a small VGG-like image CNN trained on each dataset, while for MERL Shopping, features from four CNNs in prior work (RGB, optical flow, and their cropped versions) were concatenated and reduced to 50 dimensions with principal component analysis. The later MS-TCN paper uses I3D features trained for video action recognition.

References

  1. 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.
  2. Lea, C., Vidal, R., Reiter, A., & Hager, G. D. (2016). Temporal Convolutional Networks: A Unified Approach to Action Segmentation. ECCV 2016 Workshops. arXiv:1608.08242.
  3. colincsl/TemporalConvolutionalNetworks (the authors' official code).
  4. van den Oord, A., Dieleman, S., Zen, H., et al. (2016). WaveNet: A Generative Model for Raw Audio. arXiv:1609.03499.
  5. Bai, S., Kolter, J. Z., & Koltun, V. (2018). An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling. arXiv:1803.01271.