Self-Driving Cars
Topic 28 · Part 6: Modern perception (advanced) · ⏱ about 4 h

Learning to Predict Other Road Users

Where will that car be in 3 seconds? Learn why one predicted path is not enough, train networks that predict several possible futures with probabilities, measure them with minADE, minFDE and miss rate, and build a transformer predictor in Colab.

Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the traffic world project, ready to run.Open
Show:
In this topic
Beginner

In plain words

When you drive, you guess what others will do: that car might pull out, that one will keep going. A good guess is not one path but several possibilities, each with a likelihood. Networks can learn to make exactly that kind of guess from many examples of real driving.

By the end of this topic you will be able to explain why prediction needs several possible futures, and score predictions as research benchmarks do.

Start with: the demo Try it: predict a car: click any car.

Beginner

Going deeper

The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.

Code

Why prediction must be multi-modal

In Part 4 our cars predicted others with constant velocity. That is fine for a second or two, but a car behind a slow truck might pull out, or not. The future is genuinely uncertain, and it has distinct possibilities: keep the lane, or change lane. A network trained with an ordinary squared error averages them, and predicts the car driving between the lanes, which never happens. The code shows this in a few lines.

Python · NumPy
import numpy as np

rng = np.random.default_rng(0)
# At a fork, half the cars keep straight and half change lane to the left: the future sideways position after 3 s
# is either 0 m or +3.5 m. The input (here just the speed) cannot tell which.
speed = rng.uniform(15, 30, 2000)
future = np.where(rng.random(2000) < 0.5, 0.0, 3.5)

def fit(K, steps=3000, lr=0.05):
    """K guesses (a constant each, to keep it simple), trained with "winner takes all": for every example,
    only the guess that is already closest moves towards it."""
    g = rng.normal(1.75, 0.1, K)
    for _ in range(steps):
        i = rng.integers(0, 2000, 64)
        err = (g[None, :] - future[i, None]) ** 2
        win = err.argmin(1)
        for k in range(K):
            if (win == k).any():
                g[k] -= lr * 2 * (g[k] - future[i][win == k]).mean()
    return g

print("one guess, squared error:", np.round(fit(1), 2), "m  <- the average of two futures: a car between the lanes, which never happens")
print("two guesses, winner takes all:", np.round(np.sort(fit(2)), 2), "m  <- one for each real future")
Open in playground ↗
Beginner

Multiple modes, winner takes all

The fix is to predict K futures at once (here K = 3), each with a probability. During training, only the predicted future closest to what really happened is pulled towards it (winner takes all), and the probabilities are trained to pick that winner. The modes specialise: one learns "keep going", others "change left", "change right" or "slow down".

The standard scores, used by the Argoverse and Waymo benchmarks:

  • minADE: the average distance between the true path and the best of the K predicted paths, over all time steps.
  • minFDE: the same at the final step only.
  • Miss rate: how often even the best prediction ends more than 2 m from the truth.

Our network takes the car's last 2 seconds, its lane and its six nearest neighbours, and predicts the next 3 seconds as a correction to driving on at constant speed. It was trained on 140,000 examples from the three-lane road.

Try it

Try it: predict a car

Click any car. The white line is its recent past; the coloured lines are the network's three futures, thicker when more likely. Then press Measure to score both methods on 1,000 new cases, and see the gap on the cases that matter most: lane changes.

Interactive: this part runs in your browser.

Beginner

Scenes, maps and transformers

Real predictors use much more context: the lane map (where lanes go, merge and end), traffic lights, and every agent nearby, including pedestrians and cyclists. Two ideas dominate:

  • Vectors instead of pictures: VectorNet (Gao et al., 2020) represents lanes and past paths as sets of short vectors rather than a rasterised image.
  • Attention: each agent and map element is a token, and transformer layers let every token look at every other, so the network itself works out that the car ahead and the gap in the next lane matter. Motion Transformer (MTR, Shi et al., 2022) and Wayformer are examples.

The code below builds a small version: each car's history is one token, and a transformer encoder lets the target car attend to its neighbours.

Try it

Code: download training data

40,000 cases from the three-lane road: each car's last 2 s, its 6 nearest neighbours' last 2 s, and its next 3 s.

Interactive: this part runs in your browser.

Code

Code: a transformer predictor (Colab)

For real data, Argoverse 2 and the Waymo Open Motion Dataset are free for research after registration and come with their own tools and leaderboards.

Python (Colab)
# In Google Colab (a GPU helps). Upload trajectories.npz from the recorder above.
# A transformer that predicts 3 possible futures for a car, looking at its own past and its 6 nearest neighbours.
# Each car is one "token"; attention lets the network work out which neighbours matter (the slow car ahead, the gap
# in the next lane), instead of us hand-picking features.
from google.colab import files
import numpy as np
import torch
import torch.nn as nn

d = np.load(list(files.upload())[0])
A, Y = d["agents"], d["future"]                  # (N, 7, 10, 4): x, y (left +), speed, present; (N, 15, 2)
N, K, F, DT = len(A), 3, 15, 0.2
device = "cuda" if torch.cuda.is_available() else "cpu"
cv = (A[:, 0, -1, 2])[:, None] * DT * np.arange(1, F + 1)          # constant-velocity distance along the road
target = Y.copy(); target[:, :, 0] -= cv                           # learn the correction to constant velocity
cut = int(N * 0.85)
T = lambda a: torch.tensor(a, dtype=torch.float32, device=device)
Xa, Yt, CV = T(A / np.array([30, 3.5, 30, 1])), T(target / 3.5), T(cv)

class Predictor(nn.Module):
    def __init__(s, D=128):
        super().__init__()
        s.embed = nn.Sequential(nn.Linear(10 * 4, D), nn.ReLU(), nn.Linear(D, D))
        s.who = nn.Embedding(2, D)                                 # tells the network which token is the car to predict
        s.enc = nn.TransformerEncoder(nn.TransformerEncoderLayer(D, 4, 4 * D, dropout=0.1, batch_first=True), 3)
        s.head = nn.Sequential(nn.Linear(D, D), nn.ReLU(), nn.Linear(D, K * F * 2 + K))

    def forward(s, a):
        B, M = a.shape[:2]
        h = s.embed(a.flatten(2)) + s.who(torch.tensor([1] + [0] * (M - 1), device=a.device))[None]
        missing = a[:, :, -1, 3] == 0                              # neighbours that are not there are ignored
        h = s.enc(h, src_key_padding_mask=missing)
        o = s.head(h[:, 0])
        return o[:, :K * F * 2].view(B, K, F, 2), o[:, K * F * 2:]

def loss_fn(traj, logits, y):
    err = ((traj - y[:, None]) ** 2).sum(-1).mean(-1)              # (B, K)
    best = err.argmin(1)                                           # winner takes all
    return err.gather(1, best[:, None]).mean() + 0.5 * nn.functional.cross_entropy(logits, best)

net = Predictor().to(device)
opt = torch.optim.AdamW(net.parameters(), lr=5e-4, weight_decay=1e-4)
for ep in range(30):
    net.train(); perm = torch.randperm(cut, device=device); tot = 0
    for i in range(0, cut, 256):
        b = perm[i:i + 256]
        traj, lg = net(Xa[b])
        loss = loss_fn(traj, lg, Yt[b]); opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()
    if ep % 5 == 4:
        print(f"epoch {ep + 1}: loss {tot / (cut / 256):.4f}")

net.eval()
with torch.no_grad():
    traj, lg = net(Xa[cut:])
traj = traj.cpu().numpy() * 3.5; traj[..., 0] += cv[cut:, None]
err = np.linalg.norm(traj - Y[cut:, None], axis=-1)
ade, fde = err.mean(-1).min(1), err[:, :, -1].min(1)
e_cv = np.linalg.norm(np.stack([cv[cut:], np.zeros_like(cv[cut:])], -1) - Y[cut:], axis=-1)
lc = np.abs(Y[cut:, -1, 1]) > 1.5
print(f"transformer:       minADE {ade.mean():.2f} m, minFDE {fde.mean():.2f} m, miss rate {(fde > 2).mean():.1%}, lane changes FDE {fde[lc].mean():.2f} m")
print(f"constant velocity:    ADE {e_cv.mean():.2f} m,    FDE {e_cv[:, -1].mean():.2f} m, miss rate {(e_cv[:, -1] > 2).mean():.1%}, lane changes FDE {e_cv[lc, -1].mean():.2f} m")
print("The course's small network (on hand-made features) scored about minADE 0.14 m, minFDE 0.34 m, lane changes 0.98 m.")
This code needs Google Colab (it uploads the dataset file you recorded), which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).
Check yourself

Quiz

1. Half the cars at a junction go left, half go right. A single prediction trained with squared error predicts…

2. What is minFDE?

3. In winner-takes-all training, which predicted future is updated for an example?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready