Architectural Comparison of Sequence Models and MPC Integration
Machine LearningModel answerLast updated
Detailed comparison of RNNs, LSTMs, Transformers, and Model Predictive Control, including mathematical formulations, structural trade-offs, and hybrid learning-control frameworks.
Compare the mechanics, capabilities, training dynamics, and practical trade-offs of Recurrent Neural Networks (RNNs), Long Short-Term Memory networks (LSTMs), and Transformers.
In your response:
- Explain the structural differences between sequential recurrence and self-attention, detailing how each processes temporal dependencies and scales in computational complexity.
- Outline the trade-offs of different Transformer structural configurations (encoder-only, decoder-only, and encoder-decoder) and justify when each should be chosen for a given problem setting.
- Define the core components of Model Predictive Control (MPC)—including the objective formulation, system dynamics, constraints, prediction horizon, and receding horizon mechanism.
- Detail how learned neural network models can be integrated into an MPC framework, discussing the algorithmic strategies, optimization challenges, and safety considerations involved.
Hints
Hint 1
Detail the mathematical mechanics of vanishing gradients in basic RNNs versus the additive cell state in LSTMs.
Hint 2
Compare the compute complexity of attention (length squared) versus recurrence (length times hidden size squared).
Hint 3
Frame MPC as an online optimization problem constrained by state transition dynamics, physical bounds, and safety regions.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Sequence Architectures: Mechanics & Trade-offs
Recurrent Neural Networks (RNNs)
Standard RNNs update a hidden state iteratively across time steps:
$$h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)$$
- Gradient Dynamics: Backpropagation Through Time (BPTT) requires computing product chains of Jacobians $\prod_{k=j+1}^{t} \frac{\partial h_k}{\partial h_{k-1}}$. If the dominant eigenvalues of $W_{hh}$ are less than $1$, gradients shrink exponentially with sequence length $T$ (vanishing gradient). If greater than $1$, they explode exponentially (exploding gradient). Gradient clipping mitigates explosion but cannot resolve vanishing gradients, limiting practical context to roughly 10–20 steps.
- Compute Complexity: Sequential evaluation requires $O(T)$ serial operations. Processing one step costs $O(d^2)$ operations (where $d$ is the hidden dimension), yielding an overall compute cost of $O(T \cdot d^2)$. Parallelization across time during training is impossible due to step-wise data dependencies.
Long Short-Term Memory Networks (LSTMs)
LSTMs introduce a continuous cell state $c_t$ controlled by additive gating mechanisms:
$$\begin{aligned} f_t &= \sigma(W_f [h_{t-1}, x_t] + b_f) && \text{(Forget Gate)} \ i_t &= \sigma(W_i [h_{t-1}, x_t] + b_i) && \text{(Input Gate)} \ \tilde{c}t &= \tanh(W_c [h{t-1}, x_t] + b_c) && \text{(Candidate Cell State)} \ c_t &= f_t \odot c_{t-1} + i_t \odot \tilde{c}t && \text{(Cell State Update)} \ o_t &= \sigma(W_o [h{t-1}, x_t] + b_o) && \text{(Output Gate)} \ h_t &= o_t \odot \tanh(c_t) && \text{(Hidden State)} \end{aligned}$$
- Gradient Dynamics: The cell state update $c_t = f_t \odot c_{t-1} + \dots$ creates an additive gradient highway. When $f_t \approx 1$, the partial derivative $\frac{\partial c_t}{\partial c_{t-1}} \approx 1$, letting gradients flow backward hundreds of steps without exponential decay.
- Compute Complexity: Requires $O(T \cdot d^2)$ operations (roughly $4\times$ the parameter count of a standard RNN per step). Execution remains bottlenecked by $O(T)$ sequential time steps during training.
Transformers
Transformers eliminate recurrence entirely, using scaled dot-product self-attention:
$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$
- Gradient Dynamics: The maximum path length between any two sequence positions is $O(1)$, which eliminates gradient decay over long sequence horizons. However, because positional order is not implicit in self-attention, explicit positional embeddings (sinusoidal, learned, or relative) are required.
- Compute & Memory Complexity: Matrix multiplication $QK^\top$ incurs an $O(T^2 \cdot d)$ computational cost and $O(T^2)$ memory cost for storing attention maps. This enables full horizontal parallelization across sequence lengths during training, but becomes memory-bound for long evaluation windows.
Comparative Summary
| Metric / Property | Vanilla RNN | LSTM / GRU | Transformer |
|---|---|---|---|
| Max Dependency Path Length | $O(T)$ | $O(T)$ | $O(1)$ |
| Training Parallelization | Sequential ($O(T)$ steps) | Sequential ($O(T)$ steps) | Fully Parallel ($O(1)$ steps) |
| Time Complexity per Layer | $O(T \cdot d^2)$ | $O(T \cdot d^2)$ | $O(T^2 \cdot d)$ |
| Memory Complexity per Layer | $O(T \cdot d)$ | $O(T \cdot d)$ | $O(T^2 + T \cdot d)$ |
| Online Inference Memory | $O(d)$ fixed hidden state | $O(d)$ fixed hidden state | $O(T \cdot d)$ growing KV cache |
| Inductive Bias | Strong temporal locality | Strong temporal locality | Weak (requires positional encoding) |
2. Transformer Architectures & Selection Criteria
ENCODER-ONLY DECODER-ONLY ENCODER-DECODER
(Bidirectional Context) (Causal Self-Attention) (Cross-Attention Bridge)
[X1] [X2] [X3] [X1] → [X2] → [X3] [X1] [X2] [Y1] → [Y2]
│ │ │ │ │ │ │ │ ▲ ▲
┌─┴────┴─────┴─┐ ┌─┴──────┴──────┴─┐ ┌─┴────┴─┐ ┌─┴──────┴─┐
│ Bidirectional│ │ Causal Attention│ │Encoder │───►│ Decoder │
└──────────────┘ └─────────────────┘ └────────┘ └──────────┘
Architecture Configurations
-
Encoder-Only (e.g., BERT, ViT):
- Mechanism: Uses unmasked, bidirectional self-attention where every token attends to all other tokens in the sequence.
- Best Used For: Tasks requiring holistic sequence understanding where the full context is accessible simultaneously (e.g., feature extraction, scene classification, sequence tagging, trajectory representation).
-
Decoder-Only (e.g., GPT series):
- Mechanism: Uses causally masked self-attention to ensure prediction step $t$ can only attend to tokens at indices $\le t$.
- Best Used For: Autoregressive generation tasks where the output domain matches the input domain and sampling proceeds step-by-step (e.g., standard language modeling, continuous motion generation).
-
Encoder-Decoder (e.g., T5, BART):
- Mechanism: An encoder processes the input conditioning context bidirectionally. A decoder then generates output targets, utilizing causal self-attention over previously output tokens and cross-attention over the encoder's output representations.
- Best Used For: Sequence-to-sequence mappings where input and output domains differ in length, modality, or structure (e.g., conditional multi-agent trajectory prediction, translation).
3. Model Predictive Control (MPC) Fundamentals
MPC solves an open-loop constrained optimization problem at each time step $t$ over a finite prediction horizon $N$, executes only the immediate first control action, and re-optimizes at step $t+1$ using updated state feedback.
Step t: Solve over horizon N ──► Apply u_0* only
┌───┬───┬───┬───┐
│u0*│u1 │u2 │...│
└───┴───┴───┴───┘
│
▼ (Execute u0* in physical plant)
State Feedback x_{t+1}
│
▼
Step t+1: Recede horizon by 1 step, re-solve
┌───┬───┬───┬───┐
│u1*│u2 │u3 │...│
└───┴───┴───┴───┘
Formulating the Discrete-Time Optimization Problem
$$\min_{u_{0:N-1}} \sum_{k=0}^{N-1} \ell(x_k, u_k) + V_f(x_N)$$
$$\text{subject to } x_{k+1} = f(x_k, u_k), \quad k = 0, \dots, N-1$$
$$x_k \in \mathcal{X}, \quad u_k \in \mathcal{U}, \quad k = 0, \dots, N-1$$
$$x_N \in \mathcal{X}_f$$
-
Stage Cost $\ell(x_k, u_k)$: Quantifies tracking performance and actuator strain. A standard quadratic form is: $$\ell(x_k, u_k) = (x_k - x_{\text{ref}, k})^\top Q (x_k - x_{\text{ref}, k}) + u_k^\top R u_k + \Delta u_k^\top S \Delta u_k$$ where $Q \succeq 0$, $R \succ 0$, and $S \succ 0$ penalize state deviations, control magnitude, and control slew rate ($\Delta u_k = u_k - u_{k-1}$) respectively.
-
Terminal Cost $V_f(x_N)$ & Terminal Set $\mathcal{X}_f$: Enforces closed-loop stability over finite horizons by penalizing leftover deviation beyond the prediction window.
-
System Dynamics $f(x_k, u_k)$: Equality constraints asserting that state progression matches physical motion models.
-
Hard Constraints ($\mathcal{X}, \mathcal{U}$): Inequalities representing operational boundaries (e.g., maximum acceleration, steering limits, spatial obstacles).
-
Prediction Horizon ($N$) vs. Control Horizon ($M \le N$): The prediction horizon $N$ is the lookahead window over which states are evaluated. The control horizon $M$ is the number of optimized control inputs; for steps $k \ge M$, inputs are typically held constant ($u_k = u_{M-1}$). Decreasing $M$ relative to $N$ reduces optimization dimensionality while preserving lookahead.
4. Combining Learned Neural Models with MPC
Combining statistical learning with analytical control yields two primary paradigms:
PARADIGM A: Learned Dynamics Model inside MPC
┌─────────────────────────────────────────────────────────────┐
│ Neural Network Model: x_{k+1} = f_θ(x_k, u_k) │
└──────────────────────────────┬──────────────────────────────┘
│ Predicts future trajectory
▼
┌─────────────────────────────────────────────────────────────┐
│ MPC Optimizer (e.g., MPPI / SQP): │
│ Solves min_{u} Cost subject to f_θ dynamics & hard bounds │
└─────────────────────────────────────────────────────────────┘
PARADIGM B: Neural Trajectory / Cost Generation for Classical MPC
┌─────────────────────────────────────────────────────────────┐
│ Transformer Predictor: Multi-modal agent trajectories │
└──────────────────────────────┬──────────────────────────────┘
│ Reference path & obstacle masks
▼
┌─────────────────────────────────────────────────────────────┐
│ Convex MPC (QP): Solves precise control with stability │
└─────────────────────────────────────────────────────────────┘
Integration Approaches
-
Model-Based Reinforcement Learning / Learned Dynamics ($f_\theta$):
- Replace or augment physics equations with a learned model $x_{k+1} = f_\theta(x_k, u_k)$ (e.g., an LSTM or MLP ensemble).
- Optimization solvers use sampling methods (like Model Predictive Path Integral / MPPI) or gradient descent backpropagating through the computational graph of $f_\theta$.
-
Learned Cost Functions or Warm-Start Distillation:
- Use a neural network policy to predict an initial control sequence $u_{0:N-1}^{(0)}$ to warm-start classical non-convex solvers.
- Alternatively, train models to evaluate complex spatial costs (e.g., off-road clearance from raw LiDAR inputs) fed directly into the stage cost $\ell(x_k, u_k)$.
Key Optimization Challenges & Failures
- Distribution Shift (Exploitation of Model Errors): Optimizers exploit ungrounded dynamics regions where the neural network erroneously predicts low cost.
- Fix: Train ensemble models $f_{\theta_1 \dots K}$ and incorporate predictive variance into the cost function as an ungrounded dynamic penalty.
- Differentiability & Non-Convexity: Neural models make the MPC optimization problem non-convex. Gradient-based optimization can get trapped in bad local minima. Sampling-based methods (MPPI, CEM) resolve non-differentiability but require high parallel sampling capacity.
- Latency & Real-Time Constraints: Evaluating deep models sequentially across $N$ lookahead steps within real-time control loops (e.g., $10\text{--}100\text{ Hz}$) requires aggressive model quantization or CUDA-accelerated parallel rollout kernels.
Safety and Verification
- Fallback Recovery Controllers: If the learned MPC fails to converge to a valid path, safety frameworks fallback to a certified analytical controller (e.g., simple LQR tracking a safe stopping profile).
- Control Barrier Functions (CBFs): Construct a hard invariant filter layer downstream of the learned MPC output: $$\dot{h}(x) + \gamma(h(x)) \ge 0$$ This safety layer projects the proposed action $u_0^*$ to the nearest point in the certified safe control set $\mathcal{U}_{\text{safe}}$ via quadratic programming.