Self-Driving Cars
Topic 14 · Part 2: Seeing the road · ⏱ about 2.5 h

Robustness and Running Models Live

A model that works on your test set can still fail on the road. Measure performance by condition, understand the gap between simulation and reality, fine-tune instead of starting over, and make a model fast and small enough for a car: the time budget, 8-bit weights and what they cost.

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

In plain words

A model that passes its exam can still fail in real life: at night, in rain, on a camera it has never seen. This topic is about checking a model in every condition, fixing the weak ones, and making it fast enough to run many times a second in a car.

By the end of this topic you will be able to test a model condition by condition, and explain how models are made smaller and faster.

Start with: the demo Try it: weather slices and 8-bit weights.

You do not need to train anything to follow this topic. Every demo comes with an example network that already works. Training your own in Google Colab (the Code sections) is an optional level-up you can do now or later.

Beginner

Test by condition, not on average

An average score hides the failures that matter. A model can be 95% right overall and fail badly at night, which is when people get hurt. Always break the score down by condition: weather, time of day, track, object size, distance. This is called slicing the evaluation.

Robust models come from data that covers the conditions: varied recordings, augmentation (brightness, mirroring, blur, noise), and checking the slices that are weak and collecting more of them.

Beginner

The gap between simulation and reality

A network trained only in a simulator usually performs worse on real images: the sim-to-real gap (or domain gap). Real cameras have noise, glare, lens dirt and motion blur; real roads have worn paint and endless variety. Ways to close it:

  • Domain randomisation: vary colours, textures, lighting and camera settings in simulation so much that reality looks like just one more variation (Tobin et al., 2017).
  • Fine-tuning: pre-train on lots of simulated data, then continue training on a small amount of real data.
  • Mixing data: train on simulated and real data together.
  • Better simulation: photo-realistic simulators (such as CARLA), or neural rendering that rebuilds real recorded scenes.
Beginner

Fine-tuning instead of starting over

When a new condition appears, you do not need to train from scratch. Keep the early layers (they detect edges and colours, which hardly change), and train the rest gently on the new data with a small learning rate. The risk is catastrophic forgetting: the network gets better at the new data and worse at the old. Always re-check the old test set, as this code does.

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

Code: fine-tune the U-Net on new weather

The same idea in code.

Python (Colab)
# In the same notebook as your U-Net. Upload one new recording in the weather your model finds hardest.
from google.colab import files
import numpy as np
import torch
import torch.nn.functional as F

new = load(list(files.upload())[0])
X_new, Y_new, D_new = new[0], new[1], new[2]
cut = len(X_new) * 2 // 3                        # train on the first two-thirds, test on the rest
for p in list(net.e1.parameters()) + list(net.e2.parameters()):
    p.requires_grad = False                      # keep the early layers: edges and colours are already learned
net = net.to(device)
opt = torch.optim.AdamW([p for p in net.parameters() if p.requires_grad], lr=3e-4)   # small steps: adjust, don't relearn

def own_lane_iou(X, Y):
    net.eval()
    with torch.no_grad():
        pred = np.concatenate([net((raw(X[i:i + 40]) - m) / s)[:, :7].argmax(1).cpu().numpy() for i in range(0, len(X), 40)])
    return ((pred == 1) & (Y == 1)).sum() / max(1, ((pred == 1) | (Y == 1)).sum())

print(f"before: own-lane IoU {own_lane_iou(X_new[cut:], Y_new[cut:]):.2f}")
for epoch in range(4):
    net.train()
    for b in np.array_split(np.random.permutation(cut), max(1, cut // 16)):
        out = net((raw(X_new[b]) - m) / s)
        loss = F.cross_entropy(out[:, :7], torch.tensor(Y_new[b], device=device), weight=cw) \
               + 2 * F.l1_loss(out[:, 7], torch.tensor(D_new[b], device=device))
        opt.zero_grad()
        loss.backward()
        opt.step()
print(f"after:  own-lane IoU {own_lane_iou(X_new[cut:], Y_new[cut:]):.2f}")
print(f"and on the old test set (did it forget?): {own_lane_iou(X_test, Y_test):.2f}")
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).
Beginner

The time budget

At 50 km/h a car moves 1.4 m every 100 ms. Perception, prediction, planning and control together must finish many times a second, on a computer that fits in a car and does not drain the battery. Each model gets a budget of a few to tens of milliseconds.

Ways to make a model fast enough:

  • Smaller input: our U-Net works at half size, 4 times fewer pixels.
  • Smaller networks: fewer channels, depthwise-separable convolutions (MobileNet), or distillation, where a small "student" learns to copy a big "teacher".
  • 8-bit weights (quantisation): store each weight as one of 255 levels instead of a 32-bit float. That is 4 times smaller and, on hardware with integer maths, much faster, usually for a small loss in accuracy.
  • Fusing layers: batch-norm folded into the convolution, as our exporter does, costs nothing at run time.
  • Dedicated chips and inference engines (such as TensorRT or ONNX Runtime) that run networks much faster than plain code.
Code

Code: measure the speed, and the size in 8 bits

The same idea in code.

Python (Colab)
# How long does one frame take? Run on the CPU, because a car's computer is not a Colab GPU.
import time
import torch

cpu_net = net.eval().cpu()
x = torch.zeros(1, 3, H, W)
with torch.no_grad():
    for _ in range(5):
        cpu_net(x)                               # warm up
    t0 = time.perf_counter()
    for _ in range(50):
        cpu_net(x)
ms = (time.perf_counter() - t0) / 50 * 1000
print(f"{ms:.1f} ms per frame on the CPU: {1000 / ms:.0f} frames per second")

# 8-bit weights: PyTorch's dynamic quantisation covers Linear layers; for convolutions, see the
# PyTorch quantisation docs (static quantisation) or export to ONNX and use an inference engine.
n = sum(p.numel() for p in cpu_net.parameters())
print(f"{n:,} weights: {n * 4 / 1e6:.2f} MB as 32-bit floats, {n / 1e6:.2f} MB as 8-bit integers")
This code needs PyTorch, 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).
Try it

Try it: weather slices and 8-bit weights

This runs the example U-Net on fresh frames in every kind of weather and reports the own-lane IoU for each, and how long a frame takes in your browser. Tick Round the weights to 8 bits and run it again: the model becomes 4 times smaller. How much does the IoU change?

Interactive: this part runs in your browser.

Beginner

What you have built in Part 2

Your car now has a full perception stack, trained from scratch on data you recorded: a traffic-light classifier, a detector for cars, pedestrians and lights, a U-Net for lanes, road and distance, a tracker with velocities and time to collision, and an end-to-end network to compare against. Part 3 tackles the next question: where exactly is the car? Kalman and particle filters, combining GPS, motion sensors and landmarks, and building a map.

Check yourself

Quiz

1. Why break a model's score down by weather and time of day?

2. What is catastrophic forgetting?

3. Storing weights as 8-bit integers instead of 32-bit floats makes the model…

4. What is domain randomisation?

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