TCN and Transformers
Sequence Modeling
A sequence model receives an ordered sequence of elements and produces either a single output or another sequence.
Examples of sequential inputs include:
- words or characters in text;
- time-series measurements;
- audio signals;
- video frames.
Typical sequence-modeling tasks include machine translation, time-series forecasting, video captioning, audio generation, and text summarization.
Although sequence modeling has historically been associated with Recurrent Neural Networks (RNNs), convolutional architectures and Transformers can outperform recurrent models on many tasks.
Temporal Convolutional Architectures
From 2D to 1D Convolution
A standard 2D convolution operates on two spatial dimensions and is therefore particularly suitable for images.
For sequential data, the analogous operation is a 1D convolution, where the kernel slides along a single dimension representing time or sequence position.
A discrete causal-style 1D convolution can be written as
where:
- is the input sequence;
- is a kernel of length ;
- denotes the current sequence position.
For multivariate sequences or token embeddings, each sequence element is itself a vector. Therefore, a convolutional filter must span both:
- a temporal window of elements;
- the feature or embedding dimension.
For example, if each word is represented by a -dimensional embedding and the temporal kernel covers words, the kernel has shape .
A 1D CNN can therefore model local temporal dependencies in time series and local syntactic patterns in text.
Limitation of Standard Convolutions
The main difficulty of using ordinary CNNs for long sequences is their limited receptive field.
A layer with kernel size sees only a small local neighborhood. Capturing dependencies between very distant sequence elements consequently requires:
- many convolutional layers, or
- very large kernels.
This motivates dilated convolution.
Dilated Convolution
A dilated convolution inserts gaps between the positions sampled by the kernel.
It is defined as
where is the dilation factor.
For example:
- : consecutive inputs are used;
- : every second input is used;
- : every fourth input is used.
Dilated convolutions increase the receptive field without proportionally increasing the number of parameters.
For a stack of convolutional layers with kernel size and dilation factors , assuming stride , the receptive field is
If dilation doubles at every layer,
then
Hence, the receptive field grows exponentially with network depth.
Causal Convolution
A standard convolution may use both past and future inputs when computing the representation at position .
For forecasting or autoregressive tasks, this can introduce future information leakage.
A causal convolution imposes
so the output at time depends only on observations at times .
Causality is essential whenever future observations must not influence current predictions.
Temporal Convolutional Networks
A Temporal Convolutional Network (TCN) combines:
- 1D convolutions;
- causal convolutions;
- dilated convolutions;
- residual connections.
A typical TCN consists of residual blocks with progressively increasing dilation factors, for example
with a fixed kernel size such as .
The increasing dilation gives higher layers access to progressively longer temporal histories.
TCNs Compared with RNNs
TCNs have several practical advantages over recurrent architectures such as LSTMs and GRUs.
Parallel computation
RNNs have sequential dependencies:
so computation at time depends on time .
Convolutional layers process many sequence positions simultaneously, making TCNs substantially more parallelizable.
Long effective memory
Dilated convolutions allow a TCN to capture long-range dependencies using a moderate number of layers.
Gradient propagation
Residual connections and the absence of recurrent state transitions generally make optimization more stable and reduce the severity of vanishing-gradient problems compared with long recurrent chains.
It is too strong to say that TCNs can never suffer from vanishing or exploding gradients; rather, their architecture tends to mitigate these problems.
Depth determines temporal context
Increasing network depth increases the receptive field. Therefore, the temporal history accessible to a TCN can be controlled explicitly through its architecture.
Finance Case Study
A TCN-based financial forecasting system can combine several information sources:
- price data : historical values of the DJIA;
- news data : historical news headlines;
- knowledge data : structured information obtained from resources such as Freebase and Wikidata.
The objective is binary prediction of the next market movement:
Reported baseline results include:
| Model | Accuracy | F1 Score |
|---|---|---|
| ARIMA | ||
| LSTM | ||
| CNN | ||
| TCN |
Adding textual and structured knowledge representations further improves the reported results, with the knowledge-driven model reaching
accuracy and
F1 score.
From TCNs to Transformers
TCNs impose a strong inductive bias:
nearby sequence elements interact first, while progressively larger temporal contexts are obtained through deeper and dilated convolutions.
This assumption is useful when temporal structure is approximately local and hierarchical.
However, important dependencies are not always local.
For example, in source code, the beginning of a loop or function may determine the interpretation of a variable appearing dozens of lines later.
A desirable model would therefore be able to learn directly from data which elements should interact, independently of their distance.
This motivates attention-based architectures, particularly the Transformer.
Transformer Architecture
The original Transformer consists of two main components:
- an encoder;
- a decoder.
In the original architecture introduced by Vaswani et al., both were built from stacks of layers.
Transformers are now widely used in:
- machine translation;
- text generation;
- question answering;
- dialogue systems;
- computer vision;
- multimodal learning.
The following discussion focuses primarily on the encoder.
Transformer Encoder
Suppose the input sequence contains tokens, each represented by a vector of dimension :
The encoder produces another sequence with the same dimensionality:
There is normally no temporal pooling inside the encoder itself. Instead, every input token receives a new contextualized representation.
Each encoder block contains:
- Multi-Head Self-Attention;
- a position-wise Feed-Forward Network;
- residual connections;
- Layer Normalization.
In the original Transformer, Layer Normalization is applied after each residual addition, a design commonly called Post-LN.
Feed-Forward Network
After attention, every token independently passes through the same feed-forward network.
A standard formulation is
where was originally the ReLU activation.
Typically,
followed by
The same feed-forward network is applied independently to all sequence positions.
Residual Connections
A residual connection adds the input of a module to its output:
Residual connections help preserve information and improve gradient propagation through deep architectures.
In the original Transformer encoder, a sublayer is approximately
Layer Normalization
Layer Normalization normalizes the features of each individual token rather than computing statistics across different samples in a minibatch.
Given
the mean is
and the variance is
Layer Normalization is
where:
- is a learnable scaling vector;
- is a learnable bias vector;
- provides numerical stability.
Normalization is typically performed independently for each token across its features.
LayerNorm vs BatchNorm
Batch Normalization computes statistics using multiple samples in a batch, whereas Layer Normalization computes statistics inside each individual sample or token.
Consequently, LayerNorm:
- does not depend on batch size;
- behaves consistently during training and inference;
- naturally handles variable sequence lengths;
- is particularly suitable for Transformers and other sequence models.
Core Idea of Attention
In many sequence tasks, different input elements have different relevance to a given output.
Attention allows the network to determine dynamically which elements should receive more weight.
For an input sequence
an attention mechanism produces contextualized vectors
where
The attention weights are obtained from learned compatibility scores:
Therefore, the weights are input dependent, rather than fixed parameters associated permanently with particular positions.
Attention as Content-Based Memory Access
Attention can be interpreted as a differentiable memory-retrieval mechanism.
Each memory item contains:
- a key describing what information is stored;
- a value representing the information itself.
A query represents the information currently being requested.
For query and key-value pairs
attention first computes similarity scores
The scores are normalized:
The retrieved representation becomes
Retrieval therefore depends primarily on content similarity, rather than simply on the physical distance between sequence positions.
12. Queries, Keys, and Values
Given an input matrix
the Transformer learns three linear projections:
For one attention head,
and, more generally,
Thus,
while
When queries, keys, and values all originate from the same input sequence, the mechanism is called self-attention.
13. Scaled Dot-Product Attention
The similarity between queries and keys is computed using a dot product.
For the complete sequence,
Entry measures the compatibility between the query generated by token and the key associated with token .
Scaled dot-product attention is
The softmax is applied row-wise.
Therefore,
is an attention matrix
and
Each output token representation is therefore a weighted combination of the value vectors of all tokens.
13.1 Why Divide by ?
Suppose query and key components are approximately independent, zero-mean random variables with unit variance.
Their dot product is
Its variance grows approximately proportionally to :
Large dot products can make the softmax distribution extremely peaked, producing very small gradients.
Scaling by
keeps the variance of the logits approximately constant as the key dimension increases.
14. Multi-Head Attention
A single attention head learns one set of query, key, and value projections.
Multi-Head Attention (MHA) repeats this process in parallel using different learned projections.
For head ,
The heads are concatenated:
A final projection produces
In the original Transformer,
Thus, concatenating all heads recovers dimension
Different heads can learn different types of interactions, such as syntactic, semantic, positional, or task-dependent relationships.
15. From Token Representations to Classification
The Transformer encoder returns one contextualized vector for every token:
Sequence-level classification requires converting this sequence into a single global representation.
Average Pooling
One possibility is
The pooled vector is then passed to a classifier such as an MLP.
Classification Token
Another strategy prepends a special token, commonly written [CLS], to the input.
After the Transformer layers, its contextualized embedding
is treated as a learned global sequence representation and passed to the classification head.
16. TCNs and Transformers
TCNs and Transformers both model sequential dependencies but rely on different architectural assumptions.
| Property | TCN | Transformer |
|---|---|---|
| Main operation | Convolution | Attention |
| Dependency structure | Local, progressively expanded | Direct pairwise interactions |
| Receptive field | Determined by kernel, dilation, and depth | Global within an attention layer |
| Inductive bias | Strong temporal locality | Weaker locality bias |
| Parallelism | High | High |
| Long-range dependencies | Captured through depth/dilation | Directly accessible through attention |
| Causality | Built through causal convolution | Requires attention masking when needed |
TCNs encode a structured temporal prior into the architecture, whereas Transformers learn more of the interaction structure directly from data.
17. Regression Loss Functions
17.1 Mean Squared Error
For targets and predictions ,
Because errors are squared, large errors receive disproportionately high penalties.
Consequently, MSE is:
- smooth and differentiable;
- convenient for gradient-based optimization;
- sensitive to outliers.
Minimizing expected squared error leads to estimation of the conditional mean.
17.2 Mean Absolute Error
The Mean Absolute Error is
MAE grows linearly rather than quadratically with error magnitude, making it more robust to outliers.
It is not differentiable exactly at zero error, although subgradients can be used without major difficulty in modern optimization frameworks.
Minimizing expected absolute error leads to estimation of the conditional median.
18. Regression Through Binning
A continuous regression target can be discretized into intervals called bins.
For example, for age prediction with
one might define intervals such as
The original regression problem then becomes a -class classification problem.
A classifier produces probabilities
where
A continuous estimate may be obtained using the center of the most probable bin, or through the probability-weighted average
This formulation permits the use of classification losses such as cross-entropy and also provides information about predictive uncertainty through the distribution of probability mass across bins.
Its main limitation is discretization error: very coarse bins reduce the precision of the continuous prediction.
19. Limitations of MSE and MAE
Both standard MSE and MAE are symmetric losses.
For a fixed absolute error,
overprediction and underprediction receive the same penalty.
This assumption may be undesirable when errors have asymmetric costs.
Examples include:
- energy-demand forecasting;
- risk assessment;
- financial forecasting;
- inventory management.
In addition, a point estimate such as a mean or median does not directly describe the range of possible outcomes.
These limitations motivate quantile regression.
20. Quantiles
For a random variable , a -quantile is a value satisfying, in the continuous case,
with
Examples:
corresponds to the median,
corresponds to the 90th percentile, and
corresponds to the 10th percentile.
Thus, the 90th percentile is a value such that approximately of observations are at or below it and are above it.
Median vs Mode
The median divides the probability mass into two halves.
The mode is the most probable value, or the location where the probability density reaches its maximum in a continuous distribution.
They need not coincide.
For a symmetric unimodal Gaussian distribution,
21. Quantile Loss
To estimate a specific conditional quantile rather than the mean, quantile regression uses the quantile loss, also called pinball loss.
For target , prediction , and quantile level ,
Equivalently, defining the residual
the loss is
The loss is asymmetric whenever
21.1 Case
For
the loss becomes
Thus, it is proportional to MAE.
The factor does not change the minimizer, so optimizing the quantile loss estimates the median just as minimizing MAE does.
21.2 Case
Suppose
If the model underpredicts,
the loss is
If the model overpredicts,
the loss is
Therefore, for equal absolute error magnitude, underprediction is penalized
times more strongly than overprediction.
The optimization therefore favors larger predictions until approximately of the conditional target distribution lies below the prediction.
Hence, the model learns the 90th conditional percentile.
21.3 Case
For
underprediction receives weight , while overprediction receives weight .
The model therefore learns a relatively low prediction corresponding to the 10th conditional percentile.
22. Prediction Intervals with Quantile Regression
Training separate outputs for multiple quantiles can provide an estimate of predictive uncertainty.
For example, predicting
and
gives an interval
Under correct calibration, approximately of the conditional target distribution lies between these two quantiles because
Unlike MSE regression, quantile regression does not require the target distribution to be Gaussian.
References
Bai, S., Kolter, J. Z., and Koltun, V. An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling. ICML, 2018.
Deng, S., Zhang, N., Zhang, W., Chen, J., Pan, J. Z., and Chen, H. Knowledge-Driven Stock Trend Prediction and Explanation via Temporal Convolutional Network. WWW Companion, 2019.
Selvaraju, R. R. et al. Grad-CAM: Visual Explanations from Deep Networks via Gradient-Based Localization. ICCV, 2017.
Vaswani, A. et al. Attention Is All You Need. NeurIPS, 2017.