Seq2Seq Models
Lecture 3 gave us CNNs and RNN/LSTM for time series. Those work well — but modern NLP introduced more sophisticated sequence-processing methods. Since time series are sequences too, we can borrow them.
How? An encoder / decoder architecture
LSTMs are adopted to handle inputs/outputs of variable dimensions.
The Embedding Layer
In NLP, an embedding maps a discrete input (words) into a sequence of tokens — each token a real-valued vector. There are also special tokens (e.g. <EOS> to mark when a sequence ends).
- Time series may also use an embedding layer, but no special tokens.
The Encoder & the Context Vector
- The encoder uses several LSTM layers, processing one element at a time, to map the input into a latent representation.
- This latent representation is the context vector — it summarizes the whole input sequence and is handed to the decoder.
The Decoder & Training
What the decoder does
- Decodes the context vector into the output sequence, one element at a time, by "unfolding" the LSTM.
- It begins from a starting token —
<SOS>(Start Of Sequence) or<GO>— to predict the first output element. - Each next element is predicted from the previously predicted token + the long-term memory.
- A softmax picks the most likely next token at each step.
<EOS>, even if <EOS> wasn't generated.Training: each generated token is matched against the ground truth
A specific loss compares each generated token with the ground truth and updates the weights with backpropagation. There are two ways to feed the decoder during training:
Free Running
- Each decoder step sees the actual (predicted) output of the previous step
- Realistic, but may converge slower — training is affected by error propagation
Teacher Forcing
- Each decoder step uses the ground truth of the previous step
- Faster convergence, but a higher risk of overfitting
Seq2Seq for Time Series
What changes vs NLP
- Time series are a stream of continuous values → don't necessarily need an embedding layer to obtain tokens.
- But it's often good to use a linear projection layer to map raw sensor data into a latent space. (Tokenization is only needed for categorical time series — less common.)
- The main application is usually forecasting, so the
<EOS>token is not needed (e.g. "predict the next 100 values"). - Instead of starting from
<SOS>, the decoder starts from the last n samples of the input series.
In practice the recurrent unit can be a GRU or LSTM: encoder consumes the historical data → encoder state → decoder emits the predictions Y₁…Yₙ.
Forecasting with a sliding window
Split the series: an encoder sequence (history) feeds the model, which predicts the decoder sequence (future). A sliding window moves along the series to generate many training pairs.
⭐ The Attention Mechanism
The idea of attention
Determine how much focus the decoder should place on different parts of the input when generating the current output. How? By adding many more paths between encoder and decoder — one for each input element — so each decoder step can access the output of every encoder step (similar to "skip connections").
Computing similarity
For each decoder step, compute the similarity of its output with the output of each encoder step (using the short-term memory). Usually with cosine similarity:
Attention scores (weights)
- For each decoder step you get many similarity values — one per encoder step.
- These are normalized (usually with a softmax) into attention scores / attention weights that sum to 1.
- Each score = the "importance" of an input element to producing the current output token.
- The scores are combined (sometimes via a learnable MLP) and used to output the current decoder step.
Transformers
The Transformer ("Attention Is All You Need")
- An improved, advanced version of seq2seq — the most common model in NLP today (e.g. Large Language Models), and very powerful for time series too.
- Still an encoder / decoder architecture, but the encoder processes the input in parallel (no recurrence).
- The decoder takes the previous output tokens + the context vector from the encoder, and outputs one token at a time.
The blocks of each encoder / decoder
Encoder block
- Self-Attention layer
- → Feed-Forward (fully-connected) layer
- Applies self-attention to the whole input sequence
Decoder block
- (Masked) Self-Attention
- Encoder-Decoder Attention — the same attention we saw for seq2seq!
- → Feed-Forward layer
Stacked encoders & decoders
The encoder is actually a stack of encoders, and the decoder a stack of decoders — similar to how a CNN stacks many convolutional layers to learn a more representative latent representation.
⭐ Self-Attention & Q/K/V
Self-attention
An effective and efficient way to track long-range dependencies in a sequence. For each element we compute attention scores capturing its most important semantic relationships with every other element — and this can be done in parallel for all elements (the key efficiency win over LSTMs).
Query, Key, and Value
Each element of the sequence is transformed into three vectors, obtained by multiplying the input by three weight matrices learned during training:
| Vector | Role |
|---|---|
| Query (Q) | Encodes the token when it is asking for information from other tokens |
| Key (K) | Encodes the token when it is being considered by another token (its potential to "respond" to a query) |
| Value (V) | Encodes the actual information used to update the output — weighted by the attention score |
Q and K compute the attention scores; V is used for the weighted combination.
The output of self-attention
The attention score = similarity between Q and K, computed via the dot product (the cosine similarity without the denominator, as we saw). The scores are scaled, passed through softmax (weights summing to 1), then multiplied with V to produce the resulting embedding Z:
Encoder vs Decoder self-attention
Encoder
- Self-attention over the whole input sequence
Decoder — masked
- Can not look into the future — only previously generated tokens
- Future positions are masked → masked self-attention
Multi-head self-attention
There are actually multiple self-attention layers in parallel. They produce multiple representation subspaces of the same input, improving the model.
Beyond generating sequences
- Decoder-only transformers — for autoregressive forecasting, you can use only the decoder. This is the approach of GPT models, and works for time series too. The decoder first sees the input, then generates one token at a time.
- Classification head — attach a head at the end of the decoder so it outputs the most likely class instead of generating tokens. Many time-series classification approaches follow this.
Final Quiz — Exam Style
9 MCQs + 2 open-ended. Tuned to the simulation's style, with Q1 modeled on the simulation's Seq2Seq question (Q15).
a) A Seq2Seq model maps an input sequence to an output sequence of possibly different length using two parts. The encoder (several LSTM layers) processes the input one element at a time and compresses it into a context vector — a latent representation summarizing the whole input. The decoder (also LSTMs) takes the context vector and "unfolds" it, generating the output one element at a time: it starts from a start token (<SOS>/<GO>) and predicts each next element from the previously produced token plus the long-term memory, until it emits <EOS>. It can be trained with teacher forcing (ground-truth previous token, fast but overfits) or free running (own prediction, realistic but slower).
b) For time series the input is a stream of continuous values, so no embedding/tokenization is strictly needed (a linear projection into a latent space is common; tokenization only for categorical series). Since the main task is forecasting, the <EOS> token is not needed ("predict the next n values"), and instead of starting from <SOS> the decoder starts from the last n samples of the input. A sliding window generates training pairs (history → future). The same trained model can also do imputation, anomaly detection (forecast vs observed), feature extraction, and classification.
a) A plain Seq2Seq squeezes the whole input into a single context vector, which loses information from old elements of long sequences. Attention adds direct paths from every encoder step to every decoder step, so the decoder can decide how much to focus on each input element. For each decoder step we compute the similarity between its output and each encoder step's output — using the dot product (cosine similarity without the normalizing denominator, which is faster). The similarity values are normalized with a softmax into attention scores/weights (summing to 1), representing each input's importance, then combined to produce the current output.
b) Transformers drop the LSTMs, removing long-range-dependency issues and the slow one-element-at-a-time processing. They keep an encoder/decoder structure but use self-attention: each element is turned into a Query, Key, Value (via learned weight matrices); the attention score is Q·K (dot product), scaled and softmaxed, then multiplied by V → output Z. Self-attention captures relationships between all elements and runs in parallel; multi-head attention gives several representation subspaces; the decoder uses masked self-attention (can't see the future) plus encoder-decoder attention. Since there's no recurrence, positional encoding (sine/cosine of position) is summed into the embeddings to preserve order. Variants: decoder-only (GPT-style, autoregressive forecasting) and a classification head for time-series classification.