Runtime Monitors for ML Perception

A learned detector is right almost every frame. One wrong frame can make a car brake hard for nothing, or not brake at all. A runtime monitor is small, simple code that checks every output and catches the lie.

Pick a fault and watch what reaches the planner. Then switch on a monitor and run it again. Slide the threshold both ways and count the false alarms. Then we build each monitor, piece by piece.

You need to know that a detector outputs boxes with a class and a confidence. We build the rest from zero.

Catch the lie

Ready
4.0 σ

Press Replay to drive the scene.

Toy scene, 8 s at 10 frames a second. Your car follows a lead car at 20 m/s. The fault starts at 2.0 s. The threshold is how many standard deviations of normal noise each monitor forgives. In the Missed and Frozen runs the lead car brakes hard at 2.0 s. If the camera is unhealthy, the system falls back to radar and caps the speed. All sizes, speeds and noise levels are illustrative.

Chapter 0

A model that is right 99 times

Count how often a very good detector is wrong, and see why a checker must sit beside it

A car drives down a motorway at night. Its camera network reports a truck in the lane ahead, four metres above the road. No truck floats. Yet the box arrives with a confidence of 0.93, and the planner believes it. The car brakes hard. The driver behind does not expect it.

The camera network is a learned detector: a neural network that takes an image and outputs detections. One detection is one box, with a class ("car", "pedestrian") and a confidence between 0 and 1. The detector learned to do this from millions of labelled examples. Nobody wrote its rules, so nobody can read them.

That is the strength of a learned model and its weakness. It handles scenes no engineer could describe in code. But when it is wrong, it is wrong without warning. It does not throw an error. It hands over a confident box, in the same format as every correct box.

How often does that happen? Not often, as a percentage. But percentages hide the count. A perception system runs many times a second, for hours, in thousands of cars. Try it.

Count the bad frames

Each cell is one second of driving, at 10 frames a second. A red cell holds at least one wrong frame. Move the error rate and watch one hour fill up. Then switch to a fleet.

1,000

The toy draws errors at random, independently, at the chosen rate. Real errors cluster: a confusing scene produces many wrong frames in a row. That makes them easier to catch over time and harder to catch in one frame.

A worked number

Take a detector that gets 999 frames out of 1,000 right. That sounds excellent. Now count. At 10 frames a second there are 10 × 3,600 = 36,000 frames in an hour.

bad frames per hour = 36,000 × 0.001 = 36  ·  one every 3,600 / 36 = 100 s

So a "99.9% right" detector is wrong about once every minute and forty seconds. Make it a hundred times better, wrong 1 frame in 100,000. Then one car sees a bad frame about every 2.8 hours. But a fleet of 1,000 cars driving 2 hours a day makes 72 million frames a day, so it still sees 720 bad frames every day.

Most bad frames are harmless: a parked car's box jitters, a far sign gets the wrong class. A few are not. A phantom object in the lane makes the car brake for nothing. A missed object makes it fail to brake. You cannot test your way to zero of these, because the scenes that cause them are the ones nobody thought to collect.

Here are the same numbers in Python.

# How often is a "99.9% right" detector wrong? Count frames, not percentages.
rate_hz = 10                       # perception cycles per second (illustrative)
frames_per_hour = rate_hz * 3600   # 36,000

for p_bad in (1e-2, 1e-3, 1e-4, 1e-5):
    bad_per_hour = frames_per_hour * p_bad
    hours_between = 1 / bad_per_hour
    print(f"wrong 1 frame in {round(1/p_bad):>7,}: {bad_per_hour:7.2f} bad frames/hour,"
          f" one every {hours_between * 60:7.1f} min")

# A fleet multiplies everything: 1,000 cars driving 2 hours a day.
fleet_frames = 1000 * 2 * frames_per_hour         # 72 million frames a day
print(f"fleet, 1 in 100,000: {fleet_frames * 1e-5:,.0f} bad frames a day")

The checker you can reason about

So we add a second piece of software beside the model. A runtime monitor is code that runs every cycle, reads the model's output (and sometimes its input), and decides whether that output is believable. It does not try to be a better detector. It asks simpler questions that have provable answers.

"Can a car be four metres above the road?" No: solids sit on the ground. "Can a pedestrian move ten metres in a tenth of a second?" No: that is 100 m/s. "The camera sees a car right in front; does the radar see anything there?" These questions need no learning. A person can read the code and agree that it is right.

A monitor is not magic either. It cannot know the truth. It only notices when the output breaks a rule that the truth always obeys. A lie that obeys every rule passes. And a strict rule sometimes rejects the truth. That trade is the subject of Chapter 8.

The whole lesson in one line. Put a simple, independent checker beside the learned model. Give it rules that the real world always obeys: physics, time, other sensors, geometry and input quality. When the output breaks a rule, flag it, and let the system degrade safely instead of acting on the lie.

This is daily work for a perception onboard software lead at a robotics or vehicle company. The learned models come from one team. The deterministic layer around them, which must run on time and be testable, comes from another. The monitors are where the two meet. Here is the road.

  1. The doer and the checker: the Simplex idea, and why the checker must be simpler than what it checks.
  2. Physics plausibility: sizes, speeds, accelerations and the ground. This is the hero's Physics switch.
  3. Temporal consistency: objects do not appear from nowhere or teleport. This is the hero's Temporal switch.
  4. Cross-sensor agreement: camera says car, radar says nothing. Who is right? This is the hero's Radar check.
  5. Geometric invariants: a box's pixel size must match its distance and its class.
  6. Input health: blockage, glare, blur and frozen frames. This is the hero's Input health switch.
  7. When the scene is unlike training: confidence, calibration and out-of-distribution signals, honestly.
  8. Thresholds are a trade: false alarms against misses, the ROC curve, debouncing. This is the hero's Threshold.
  9. What a monitor may do: flag, drop, fall back, degrade, and log. Never silently fix.
  10. Testing a monitor: fault injection, replay and coverage.
  11. The monitor bench: every fault and every monitor at once. Break it on purpose.
  12. Interview arsenal: cheat sheet, design prompts, drills and debugging scenarios.
An interviewer asks: "Our detector is 99.9% accurate per frame. Why would we still need a runtime monitor?"

Chapter 1

The doer and the checker

Pair a clever part you cannot verify with a simple part you can, and switch before it is too late

A learner driver sits at the wheel. An instructor sits beside them with a second brake pedal. The instructor does not drive. They watch, and they step in only when the car is about to leave the safe zone. The learner is skilled but unpredictable; the instructor is predictable and always there.

Software can copy that arrangement. The doer is the complex part: the learned detector, or a learned planner. It does the real work and does it well most of the time, but nobody can prove what it will do in every case. The checker is the simple part. It watches the doer's output and decides whether it is safe to use.

The third part is the fallback: a simple behaviour that is always safe enough, such as "brake gently in lane" or "use the radar only and slow down". When the checker objects, the system switches from the doer to the fallback.

This pattern has a name. The Simplex architecture, from real-time control research in the 1990s, puts a high-performance controller beside a simple, verified safety controller. A decision module switches to the safety controller whenever the system state nears the edge of the region it can still recover from.

Switch before the line

A learned lane keeper drives. Press Make the doer swerve: it starts drifting toward the line. The checker predicts where the car would stop drifting if the fallback took over now. Change how fast the checker reacts and how hard the fallback can steer.

0.10 s
2.0 m/s²

Toy: the car's centre may move 0.85 m from the lane centre before a wheel touches the line. The doer's swerve drifts sideways at up to 1.2 m/s. The fallback cancels sideways speed at the chosen rate, then steers back. The checker is designed for a 0.2 s delay (its 50 ms cycle plus hand-over) and 2.0 m/s² of steering. Numbers are illustrative.

When must the checker switch?

The checker cannot wait until the car touches the line. The fallback needs room to work. So the checker asks: "If I hand over now, where does the drift stop?" That depends on three things: the sideways speed, the checker's own delay, and how hard the fallback can steer.

ystop = y + v td + v² / (2 a)    switch if   ystop ≥ yedge
ystop
where the sideways drift would stop if the fallback took over now, in metres from the lane centre
y
the car's sideways position now
v
its sideways speed, toward the line
td
the delay before the fallback acts: checker cycle plus hand-over
a
how fast the fallback can cancel sideways speed
yedge
the limit: here 0.85 m, where a wheel touches the line

The last term is the same as a braking distance, turned sideways. Worked: the car drifts at v = 0.8 m/s. The checker delay is 0.1 s and the fallback cancels sideways speed at 2 m/s².

travel during the delay: 0.8 × 0.1 = 0.08 m  ·  while cancelling: 0.8² / (2 × 2) = 0.16 m  ·  switch by y = 0.85 − 0.24 = 0.61 m

So the checker must hand over while the car is still 0.24 m inside the limit. Double the drift speed to 1.6 m/s and the margin becomes 0.16 + 0.64 = 0.80 m: the checker must switch almost at once. The faster things go wrong, the earlier the checker must act. Try it in the device with a long delay and a weak fallback.

Why the checker must be simple and independent

The whole argument rests on one claim: we trust the checker more than the doer. That only holds if the checker is much simpler. A checker with 300 lines of plain arithmetic can be reviewed line by line, tested on every branch, and timed to the microsecond. A checker that is itself a neural network brings back the problem it was meant to solve.

It must also be independent: it must not fail for the same reason as the doer. If the checker reads the same corrupted image buffer, or shares the same wrong calibration file, one fault breaks both. This is called a common-cause failure. Independence means separate inputs where you can, separate code, and ideally separate timing, so a hang in one does not freeze the other.

In perception, a monitor rarely switches the whole car to a fallback. More often it judges each detection, or each frame, and passes a verdict to the rest of the system. So the verdict needs a clear shape. Here is one, in C++, with a reason code on every result.

// A monitor's verdict: a small value type that always says WHY.
#include <array>
#include <cstddef>
#include <cstdint>

enum class Reason : std::uint8_t {      // one code per check, so logs can be counted
  Ok = 0, SizeImplausible, SpeedImplausible, OffGround, Teleport, Unconfirmed,
  NoRadarSupport, CameraMiss, GeometryMismatch, StaleInput, BadExposure, Blocked
};
enum class Severity : std::uint8_t { Info, Degrade, Fallback };

struct MonitorResult {
  Reason reason = Reason::Ok;
  Severity severity = Severity::Info;
  std::uint16_t object_id = 0;           // which detection; 0 means the whole frame
  float score = 0.0f;                    // how far past the bound, in standard deviations
  bool ok() const { return reason == Reason::Ok; }
};

// Fixed capacity, chosen at design time: no heap in the cycle.
template <std::size_t kMax>
struct ResultList {
  std::array<MonitorResult, kMax> items{};
  std::size_t n = 0;
  std::size_t dropped = 0;               // overflow is counted, never hidden
  void push(const MonitorResult& r) { if (n < kMax) items[n++] = r; else ++dropped; }
  bool any(Severity s) const {
    for (std::size_t i = 0; i < n; ++i) if (items[i].severity == s) return true;
    return dropped > 0 && s == Severity::Fallback;   // lost results: assume the worst
  }
};

// Simplex-style switch: trust the doer while the checker is quiet.
enum class Source : std::uint8_t { Learned, Fallback };
template <std::size_t kMax>
Source choose(const ResultList<kMax>& r, Source cur, int& clean, int return_after) {
  if (r.any(Severity::Fallback)) { clean = 0; return Source::Fallback; }   // switch at once
  if (cur == Source::Fallback && ++clean < return_after) return cur;       // return slowly
  return Source::Learned;
}

Four choices in that code matter. Every result carries a Reason, so a log can count "how many StaleInput flags per hour" instead of "how many flags". The list has a fixed capacity, so the cycle never allocates memory. Overflow is counted, and the decision treats lost results as the worst case. And the switch back to the doer is slow on purpose, as Chapter 8 explains.

Where it goes wrong

Failure mode: the checker trips too late. The checker uses the right rule, but it measures the margin without its own delay, or with a fallback stronger than the real one. On the test track it looks fine. On a wet road the fallback steers less hard, and the car touches the line after the switch.

How to diagnose it: log, at every switch, the predicted stop point and the actual peak position. If the actual peak is often beyond the prediction, the model inside the checker is optimistic. Fix it with the worst-case fallback strength and the measured worst-case delay, not the average. The safety-critical architecture lesson calls the time you have to react the fault-tolerant time interval.

An interviewer asks: "In a Simplex design, why is the safety controller deliberately simple, and when must the switch happen?"

Chapter 2

Physics plausibility

Reject boxes that break the rules every real object obeys: size, speed, acceleration and the ground

Back to the floating truck. A box says "truck", 12 m long, its bottom edge four metres above the road. You do not need a neural network to know that is wrong. Trucks are big, but they are not 40 m long. They move, but they do not hover. Real objects obey physics, so a detection that breaks physics is not a real object.

A physics plausibility check tests each detection against limits that hold for its class. The limits come in four families.

A fifth rule is simple too: two solids cannot share the same space. Two boxes that overlap by half their area are one object counted twice, or one of them is false.

Is this object possible?

Pick a class and set what the detector claims. The dashed outlines show the smallest and largest plausible box for the class. Each lamp is one check. Try the presets.

4.5 m
1.80 m
0.0 m
20 m/s

Limits are the illustrative table in the C++ below, with 0.2 m of slack for size and ground, and 3 m/s for speed. A real table is built from labelled data and reviewed for the place the vehicle drives.

The acceleration check, worked

A detector gives positions, not accelerations. So the monitor estimates acceleration from three positions of the same object, Δt apart. First two speeds, then the change in speed:

a ≈ ( p2 − 2 p1 + p0 ) / Δt²
a
the estimated acceleration, in m/s²
p0, p1, p2
three positions of one object along its path, oldest first, in metres
Δt
the time between two of those positions, in seconds

A pedestrian is seen at 10.0 m, then 10.7 m, then 15.4 m, with Δt = 0.5 s between them. The first speed is 0.7 / 0.5 = 1.4 m/s, a normal walk. The second is 4.7 / 0.5 = 9.4 m/s.

a = (15.4 − 2 × 10.7 + 10.0) / 0.5² = 4.0 / 0.25 = 16 m/s²

A person can push off at a few m/s². Take 6 m/s² as the illustrative limit. Add slack for noise, which we size next. If the slack is 5.9 m/s², the bound is 11.9 m/s². The estimate of 16 is above it: flag. The track probably jumped to a different person.

The trap: differences amplify noise

Why use Δt = 0.5 s and not one frame, 0.1 s? Because each position carries noise, and the formula divides by Δt². With position noise of standard deviation σ, the three noises add up through the weights 1, −2 and 1:

σa = √(1² + 2² + 1²) · σ / Δt² = √6 · σ / Δt²
σa
the noise in the acceleration estimate, as a standard deviation
σ
the noise in one position, as a standard deviation
Δt
the spacing between the three positions

σ = 0.2 m, Δt = 0.1 s: σa = 2.45 × 0.2 / 0.01 = 49 m/s²  ·  Δt = 0.5 s: 2.45 × 0.2 / 0.25 = 1.96 m/s²

At one frame, the noise alone is 49 m/s², eight times the limit. A frame-to-frame acceleration check would flag almost every walking person. At 0.5 s it falls 25 times, to about 2 m/s², and three standard deviations of slack is the 5.9 we used above.

Differentiate the noise

A person walks at a steady 1.4 m/s, so the true acceleration is zero. Each bar counts acceleration estimates from noisy positions. Warm lines mark the ±6 m/s² limit. Widen the spacing or shrink the noise.

0.20 m
0.10 s

2,000 estimates from seeded Gaussian position noise. Bars beyond the plot edge pile up in the end bins.

So a good physics monitor reads velocity and acceleration from the track, the filtered estimate a tracker keeps for each object, or from a wide time baseline. The multi-target tracking lesson builds that track. The trade is delay: a 0.5 s baseline needs 0.5 s of history, so it cannot judge an object that just appeared. Chapter 3 covers new objects.

Here is the check in C++. The limits live in one constexpr table, so a reviewer reads them in one place, and the compiler bakes them into read-only memory.

// Physics plausibility for one detection. Uses Reason from Chapter 1.
#include <cmath>
#include <cstdint>

enum class Cls : std::uint8_t { Pedestrian = 0, Car = 1, Truck = 2 };
struct Range { float lo, hi; };
struct Limits { Range len, wid, hgt; float v_max, a_max; };

// Illustrative limits (metres, m/s, m/s^2). A real table comes from data
// and from the operating domain, and it is reviewed like code.
constexpr Limits kLimits[3] = {
  {{0.2f, 1.2f}, {0.2f, 1.2f}, {0.8f, 2.2f}, 10.0f,  6.0f},   // pedestrian
  {{3.0f, 6.0f}, {1.4f, 2.2f}, {1.2f, 2.2f}, 70.0f, 12.0f},   // car
  {{5.0f, 25.f}, {2.0f, 2.7f}, {2.5f, 4.5f}, 40.0f,  8.0f},   // truck
};

struct Box3 { Cls cls; float z_bottom, len, wid, hgt; };
struct Motion { float vx, vy, ax, ay; };  // from the TRACK, not from two raw frames

inline float excess(float v, Range r) { return v < r.lo ? r.lo - v : (v > r.hi ? v - r.hi : 0.f); }

// slack: how much measurement error we forgive, in metres (k times sigma).
inline Reason check_physics(const Box3& b, const Motion& m, float slack, float v_slack) {
  const Limits& L = kLimits[static_cast<int>(b.cls)];
  if (!std::isfinite(b.len) || !std::isfinite(b.wid)) return Reason::SizeImplausible;  // NaN in, flag out
  if (excess(b.len, L.len) > slack || excess(b.wid, L.wid) > slack ||
      excess(b.hgt, L.hgt) > slack)       return Reason::SizeImplausible;
  if (std::fabs(b.z_bottom) > slack + 0.5f) return Reason::OffGround;      // solids touch the road
  const float v = std::hypot(m.vx, m.vy), a = std::hypot(m.ax, m.ay);
  if (v > L.v_max + v_slack)              return Reason::SpeedImplausible;
  if (a > L.a_max + v_slack)              return Reason::SpeedImplausible;  // same code, logged with score
  return Reason::Ok;
}

Two lines deserve a second look. A NaN size fails every comparison, so without the isfinite test a NaN box would pass every check. And the speed comes from a Motion that the tracker filled, not from two raw frames.

Where it goes wrong

Failure mode: the ground plane is not flat. On a hill crest or a ramp, the road ahead is above or below the flat plane the monitor assumes. Every car on the slope looks like it floats or sinks, and the ground check floods with flags.

How to diagnose it: plot ground-check flags against road pitch from the map or the vehicle's own pitch sensor. A cluster on slopes means the model of the road, not the detector, is wrong. Fix it with a local ground estimate (from lidar points, or from the map) and a slack that grows with range.

An interviewer asks: "Why not check acceleration from the last three frames at 10 Hz? It reacts fastest."

Chapter 3

Temporal consistency

Use the past to judge the present: objects do not appear from nowhere, teleport or vanish

A pedestrian walks along the kerb. In one frame the detector puts her at 30 m. In the next frame, a tenth of a second later, it puts her at 40 m. Then back at 30 m. She did not run at 100 m/s and back. The detector briefly matched her to a different blob, or to nothing at all.

A single frame cannot reveal that. A sequence can. The world changes smoothly: things move along paths, at speeds they can reach. A temporal consistency check compares each new detection with what the past says should be there.

Three questions cover most cases. Did this object appear from nowhere at full confidence? Is it where its history predicts, or did it jump? Did an object that was there a moment ago vanish while it was still in plain view?

Question 1: did it just appear?

Real objects enter the scene at the edges, or from behind something, and they are seen again and again. Many false detections are one-frame flickers: a reflection, a shadow, a burst of sensor noise. So a monitor holds a new object back until it has been seen in M frames in a row. That rule is a persistence counter. Until it passes, the object is held: kept and watched, not deleted, but not yet given to the planner.

How well does that work? If a flicker appears in any one frame with probability 0.01, and frames are independent, then three in a row has probability 0.01³ = one in a million. The price is delay. With M = 3 at 10 Hz, a real object reaches the planner 0.2 s after its first detection. At 20 m/s your car covers 4 m in that time.

Question 2: is it where it should be?

For an object with a history, a tracker predicts where it should be now. The gap between the detection and the prediction is the innovation. A monitor divides it by the spread it expects, and gets a distance in standard deviations:

z = √( (Δx / σx)² + (Δy / σy)² )    flag if   z > k
z
how surprising the detection is, in standard deviations
Δx, Δy
the innovation: detection minus prediction, along and across the road, in metres
σx
the expected spread along the road: the track's own doubt plus the detector's noise
σy
the same, across the road
k
the threshold: the hero's slider

This is the same gate a tracker uses to decide which detection belongs to which track. The multi-target tracking lesson derives it with the full covariance, and data association covers it from the fusion side. Here we use it for a different job: not "which track does this belong to?" but "is this believable at all?"

jump 6 m, σ = 0.35 m: z = 6 / 0.35 = 17.1  ·  normal noise, 0.3 m and 0.2 m off: z = √(0.86² + 0.57²) = 1.03

With k = 4, the jump is flagged and the normal detection passes. A flagged detection is not fed into the track, so the track keeps its sane estimate and the next good detection lands inside the gate again.

Question 3: did it vanish?

A confirmed object that disappears in the middle of the view, with nothing in front of it, is suspicious. The detector may have missed it. So the monitor keeps the track alive for a short time, predicting it forward. That is called coasting. The planner keeps seeing the object, marked as coasting, instead of seeing an empty road.

Judge each frame by its history

The top plot is distance ahead over 6 s. The warm band is the gate around the lead car's prediction. At 1.8 s the lead car's box teleports. At 3.0 s a ghost appears. At 4.4 s a real pedestrian appears. The strips below show each newcomer's persistence counter.

2 frames
3 frames
4.0 σ

Toy stream at 10 Hz with seeded noise of 0.2 m. The gate uses σ = 0.35 m. The teleport is 6 m for two frames. Persistence here means M frames in a row.

Push the ghost to 4 frames with M = 3: it passes. A persistent ghost, such as a person printed on a billboard or a reflection in a shop window, is seen every frame. No temporal rule can stop it, because it is consistent over time. That is why monitors come in families: Chapter 4's radar check catches what time cannot.

Here is a persistence counter and a gate in C++. One byte holds the last 8 frames, so the whole history of a track costs one byte.

// Temporal consistency: a persistence counter and an innovation gate.
#include <cstdint>

// The last 8 frames as bits; bit 0 is this frame. One byte per track, no heap.
struct Persistence {
  std::uint8_t bits = 0;
  void push(bool seen) { bits = static_cast<std::uint8_t>((bits << 1) | (seen ? 1u : 0u)); }
  int hits(int n) const {                          // how many of the last n frames had a detection
    int c = 0;
    for (int i = 0; i < n; ++i) c += (bits >> i) & 1u;
    return c;
  }
  bool confirmed(int m, int n) const { return hits(n) >= m; }   // M of N
  int misses_in_a_row() const {
    int c = 0;
    while (c < 8 && !((bits >> c) & 1u)) ++c;
    return c;
  }
};

// Innovation gate: is the new detection where the track said it would be?
// sigma2 is the expected squared error (track spread plus detector noise), per axis.
inline bool in_gate(float dx, float dy, float sx2, float sy2, float k) {
  if (!(sx2 > 0.f) || !(sy2 > 0.f)) return false; // a broken covariance is not a pass
  const float d2 = dx * dx / sx2 + dy * dy / sy2;  // squared distance in standard deviations
  return d2 <= k * k;
}

// What the planner may see: confirmed and in the gate, or coasting for a short while.
enum class TrackUse : std::uint8_t { Hold, Pass, Coast, Drop };
inline TrackUse decide(const Persistence& p, bool gated_hit, int m, int n, int max_coast) {
  if (gated_hit) return p.confirmed(m, n) ? TrackUse::Pass : TrackUse::Hold;
  if (p.misses_in_a_row() <= max_coast && p.hits(8) >= m) return TrackUse::Coast;
  return TrackUse::Drop;
}

Where it goes wrong

Failure mode: the gate swallows its own object. A car brakes hard. The tracker's model assumed steady speed, so the prediction runs ahead of the car. The real detections fall outside the gate and get flagged as "teleports". The track coasts on its wrong prediction while the real car slows.

How to diagnose it: plot the innovation z over time for flagged tracks. A teleport is one spike. A manoeuvre is a ramp: z grows frame after frame in the same direction. Fix it with a motion model that allows braking: a larger process noise, or a second model as in the IMM chapter of the tracking lesson. Then log every gate rejection with its z, so the ramps are visible.

An interviewer asks: "A billboard shows a photo of a person. Your temporal consistency monitor passes it. Why, and what catches it instead?"

Chapter 4

Cross-sensor agreement

Ask a second sensor, but only count its silence where it could have seen

The camera network reports a car 18 m ahead, in your lane, with confidence 0.91. The radar, which measures distance by bouncing radio waves off things, reports nothing there. One of them is wrong. Which one?

A camera and a radar fail in different ways. A camera is fooled by pictures, glare and shadows, but it sees shape and class well. A radar is fooled by metal guardrails and bridges, and it sees people poorly. But it measures distance and closing speed directly, and a painted image never fools it. Because their failures differ, their agreement is strong evidence. A cross-sensor check uses that.

Silence is only evidence where the sensor can look

"Radar sees nothing" means something only if radar should have seen something. This idea is called expected detection. Before you count the radar's silence against the camera, check four things.

Each case gives one of three answers: the radar should see it, it should not, or nobody knows. Only the first answer lets silence count as evidence.

Who is right?

Drag the blue camera box around the scene. The purple wedge is the radar's view; the dots are its returns. The truck hides what is behind it. Read the verdict, then change the class and the policy.

Toy geometry: radar view ±40° out to 85 m, camera view ±50° out to 75 m. Agreement uses σ = 0.5 m along and 0.8 m across, and k = 4. Radar sees pedestrians beyond 30 m too weakly to count its silence.

How strong is the evidence? A worked number

Say 1 in 100 new camera objects is a ghost. Say radar misses a real car in a single frame 1 time in 10 (illustrative), independently from frame to frame. A ghost never makes a radar return.

P(ghost | silent) = P(silent | ghost) P(ghost) / P(silent)
ghost
the camera detection is false; prior P = 0.01
silent
radar shows no return near the detection, in a place it should see

one silent frame: 0.01 / (0.01 + 0.99 × 0.1) = 0.01 / 0.109 = 0.092

three silent frames: P(silent³ | real) = 0.1³ = 0.001  ·  0.01 / (0.01 + 0.99 × 0.001) = 0.91

One silent frame moves the odds from 1% to 9%: weak evidence. Three silent frames in a row move them to 91%. This is why the toy's radar check, and the hero's, treats new and old objects differently. A brand-new object with no radar support is flagged at once, because most of its trust is still unearned. An established car is flagged only after three silent frames in a row, so one radar dropout does not cause a false alarm.

Voting or veto

How do you combine the two opinions? The device's three policies show the main choices.

PolicyA camera ghostA pedestrian radar cannot seeA car both see
Either sensor (OR)kept: phantom brakingkeptkept
Both sensors (AND)droppeddropped: a missed personkept
Expected detection (veto only where radar should see)droppedkept, with lower trustkept

OR minimises misses and maximises ghosts. AND does the reverse. A veto that applies only where the second sensor is expected to see gets most of both. With three or more independent sources you can vote, "two out of three", which tolerates any single sensor being wrong.

Here is the check in C++, in three steps: expected detection, the distance to the nearest return, and the verdict.

// Cross-sensor agreement: should the radar see this camera detection, and does it?
#include <cmath>
#include <cstddef>

enum class Expect : unsigned char { Yes, No, Unknown };
struct RadarCfg { float max_range, half_fov, min_range; };       // metres, radians
struct Occluder { float az_lo, az_hi, range; };                  // an angle interval in front of us

// Step 1: expected detection. Silence only counts as evidence where the radar can look.
inline Expect radar_should_see(float x, float y, bool weak_reflector, const RadarCfg& c,
                               const Occluder* occ, std::size_t n_occ) {
  const float r = std::hypot(x, y), az = std::atan2(y, x);
  if (r < c.min_range || r > c.max_range || std::fabs(az) > c.half_fov) return Expect::No;
  for (std::size_t i = 0; i < n_occ; ++i)                       // hidden behind something closer?
    if (az >= occ[i].az_lo && az <= occ[i].az_hi && occ[i].range < r) return Expect::No;
  if (weak_reflector && r > 30.f) return Expect::Unknown;      // a person far away: maybe, maybe not
  return Expect::Yes;
}

// Step 2: agreement. Distance to the nearest radar return, in standard deviations.
struct Ret { float x, y; };
inline float nearest_sigma(float x, float y, const Ret* rs, std::size_t n, float sx, float sy) {
  float best = 1e9f;
  for (std::size_t i = 0; i < n; ++i) {
    const float dx = (rs[i].x - x) / sx, dy = (rs[i].y - y) / sy;
    const float d = std::sqrt(dx * dx + dy * dy);
    if (d < best) best = d;
  }
  return best;
}

// Step 3: verdict. New objects must agree now; established ones get a few misses.
enum class Agree : unsigned char { Confirmed, Abstain, Disagree };
inline Agree agree(Expect e, float d_sigma, float k, int silent_frames, bool is_new, int patience) {
  if (e != Expect::Yes) return Agree::Abstain;                   // no evidence either way
  if (d_sigma <= k) return Agree::Confirmed;
  return (is_new || silent_frames >= patience) ? Agree::Disagree : Agree::Abstain;
}

Note that Abstain is a real answer, not a pass. The rest of the system can treat an object with no independent support differently from one that two sensors agree on. For example, it can ask for more confidence before braking hard for it.

Where it goes wrong

Failure mode: the sensors disagree because they are misaligned. After a minor knock, the radar points half a degree to the left. Every object now sits 0.44 m to the side at 50 m (50 × tan 0.5°). Far cars start failing agreement, and the false alarms grow with range.

How to diagnose it: for every agreed pair, log the camera position minus the radar position. Average it per range band. A bias that grows linearly with range is an angle error. That is a calibration fault, and it belongs to Chapter 6's input health.

An interviewer asks: "The camera reports a pedestrian at 45 m and the radar shows nothing. Do you drop the pedestrian?"

Chapter 5

Geometric invariants

Check one box three ways: its pixel size, its ground contact and its claimed distance must agree

A detector draws a box around a car in the image and says "30 m away". The box is 50 pixels tall. Is that consistent? You can answer without any learning, using the way a camera turns the world into pixels.

A camera is close to a pinhole camera: light from a point in the world travels in a straight line through one point, the lens centre, onto the sensor. Two consequences follow. Far things look small, in exact proportion to distance. And on a flat road, the farther away something stands, the closer its feet appear to the horizon, the image row where the road plane meets the sky. The camera geometry lesson builds this model in full.

Two independent distance estimates

From size. An object of real height H, at distance Z, appears h pixels tall: h = f H / Z. The focal length f, in pixels, is a fixed property of the camera that calibration measures. Turn it around and the box gives a distance range, from the class's range of heights.

Z = f H / h     Zg = f hc / (vb − v0)
Z
the distance implied by the box's size, in metres
f
the focal length, in pixels
H
the real height of the object, from the class prior: a car is about 1.4 to 1.6 m
h
the box height in the image, in pixels
Zg
the distance implied by where the box touches the road
hc
the camera's height above the road, in metres
vb
the image row of the box's bottom edge, counted downward
v0
the image row of the horizon

From the ground. The bottom edge is where the object meets the road. On a flat road, that row alone gives the distance: the second formula. A bottom edge at or above the horizon has no solution. The object would have to float, or be infinitely far.

A worked number

The camera has f = 1,000 px and sits 1.4 m above the road. The box is 50 px tall, and its bottom edge is 47 px below the horizon. The class is car, 1.4 to 1.6 m tall. The model claims 30 m.

from size: 1,000 × 1.4 / 50 = 28 m to 1,000 × 1.6 / 50 = 32 m  ·  from the ground: 1,000 × 1.4 / 47 = 29.8 m

Three numbers, three methods, all near 30 m: consistent. Now the same model says "truck at 20 m" for a box 60 px tall. Trucks are about 3 to 4 m tall, so size says 1,000 × 3 / 60 = 50 m to 1,000 × 4 / 60 = 67 m. The claim of 20 m is far outside. Either the class is wrong (it is a car, 1.2 m at 20 m) or the distance is wrong. Either way, do not trust the box.

Three ways to measure one box

Left: the scene from the side, with the camera on the left. Right: what the camera sees, with the horizon as a dashed line. Move the object's real distance, the distance the model claims, and how high it floats.

30 m
30 m
0.0 m

f = 1,000 px, camera 1.4 m above a flat road, 15% tolerance on each estimate for pitch and slope. Class heights are typical ranges: car 1.4 to 1.6 m, truck 3.0 to 4.0 m, pedestrian 1.5 to 1.9 m.

Set the float to 4 m with a truck at 30 m. The bottom edge rises above the horizon: no ground distance exists, so the check reports OffGround. That is the floating truck from Chapter 0, caught by geometry alone. Set the float to 1 m instead. Now a ground distance exists, but it is far too large, and it disagrees with size: GeometryMismatch.

Other geometric invariants follow the same idea. A 3D box projected back into the image should land on the 2D box the detector drew, within a few pixels: this is a reprojection check. Two cameras that overlap should see the same object at the same 3D point. And a box's bottom should not sit above the horizon unless the road climbs.

// Geometric invariants: three distance estimates for one box must agree.
#include <cmath>

struct Cam { float f_px, v0_px, height_m; };   // focal length, horizon row, mounting height
struct Box2 { float top_px, bottom_px; };      // image rows, growing downward
struct Prior { float h_lo, h_hi; };            // typical real height of this class, metres

// (a) From the ground contact: the bottom edge row tells distance on a flat road.
inline float z_from_ground(const Cam& c, const Box2& b) {
  const float dv = b.bottom_px - c.v0_px;      // rows below the horizon
  return dv > 0.5f ? c.f_px * c.height_m / dv : INFINITY;   // at or above the horizon: floating
}

// (b) From the class size: a box h pixels tall of real height H is at Z = f H / h.
inline void z_from_size(const Cam& c, const Box2& b, const Prior& p, float& z_lo, float& z_hi) {
  const float h = b.bottom_px - b.top_px;
  z_lo = c.f_px * p.h_lo / h;
  z_hi = c.f_px * p.h_hi / h;
}

// (c) The claimed distance (from the model's 3D head) must sit inside both.
// rel_tol: allowed relative error of the ground estimate (pitch, slope), e.g. 0.15.
inline Reason check_geometry(const Cam& c, const Box2& b, const Prior& p,
                             float z_claimed, float rel_tol) {
  if (!(b.bottom_px > b.top_px + 1.f)) return Reason::GeometryMismatch;   // a box with no height
  const float zg = z_from_ground(c, b);
  if (!std::isfinite(zg)) return Reason::OffGround;           // bottom edge above the horizon
  float lo, hi; z_from_size(c, b, p, lo, hi);
  const bool ground_ok = std::fabs(z_claimed - zg) <= rel_tol * zg;
  const bool size_ok = z_claimed >= lo * (1.f - rel_tol) && z_claimed <= hi * (1.f + rel_tol);
  return (ground_ok && size_ok) ? Reason::Ok : Reason::GeometryMismatch;
}

Where it goes wrong

Failure mode: the road is not flat. Going up a hill, the road ahead rises. A car on the slope stands higher in the image than the flat model expects, so the ground distance comes out too long, and the check flags real cars.

How to diagnose it: the flags cluster at the same places on every drive, where the map shows slopes, and they affect every car, not one. Size-based estimates stay consistent with the claim. Fix it with a road surface from the map or from lidar, or widen the tolerance with range and fall back on the size check alone there.

An interviewer asks: "A detection says truck, 20 m away, and its box is 60 px tall with f = 1,000 px. What does a geometry monitor conclude?"

Chapter 6

Input health

Check what the model is looking at before you trust what it says

A car leaves a tunnel into low sun. For half a second the camera image is almost pure white. The detector still runs. It still outputs boxes, or no boxes, with confidences. Nothing in its output says "I could not see".

A model is only as good as its input. Many failures start before the model runs: a lens covered in mud, glare, darkness, fog, a cable fault that delivers the same frame again and again. An input health monitor checks the input itself with cheap measurements. If the input is bad, every output from it is suspect, however confident it looks.

Cheap statistics that catch a lot

You do not need to understand an image to know it is unusable. A few numbers, computed in one pass over the pixels, catch most bad inputs.

Is the data fresh?

The most dangerous input fault looks perfect. A driver stalls, and the pipeline delivers the last good frame again, and again. Every frame is sharp and well exposed. It is simply old. Two checks catch this. A frame counter: every new frame carries a number one higher than the last; a repeat means a stuck pipe. And the timestamp age: the time now minus the time the frame was captured.

camera at 30 Hz: period = 1 / 30 = 33 ms  ·  age limit of 3 periods = 100 ms  ·  at 20 m/s, 100 ms is 2 m of travel

So a frame older than 100 ms is flagged as stale, and the system has acted on old data for at most about 2 m. The limit is illustrative: it comes from how much delay the downstream function can tolerate. Both timestamps must come from one shared clock, or the age is meaningless.

Is the camera fit to trust?

A small synthetic camera frame, and the numbers a monitor computes from it. Pick a fault and raise its severity. Warm outlines mark tiles that look blocked. Each bar shows its limit as a warm tick.

0.70

A 96 by 54 pixel greyscale scene drawn in code; every statistic is computed live from these pixels. Limits are illustrative: saturated over 25%, dark over 30%, sharpness under 4.0 grey levels a pixel, age over 100 ms. A tile counts as blocked when its sharpness is under 1.5 and it is uniform.

Try the mud splash at full severity. The whole-image sharpness drops only a little, and it may stay above the limit. The tile check sees it at once. That is why real input monitors work on regions, not only on the whole frame.

Here is the whole-frame version in C++: one pass, every other row, integer sums, no heap. It runs in a fraction of a millisecond on a small embedded core, which matters because it runs on every frame of every camera.

// Input health: cheap statistics of one camera frame, in one pass, no heap.
#include <cstdint>
#include <cstdlib>

struct Frame { const std::uint8_t* px; int w, h; std::uint32_t counter; std::int64_t stamp_us; };
struct Health { float mean, sat, dark, sharp; std::int64_t age_us; bool repeated; };

inline Health measure(const Frame& f, std::int64_t now_us, std::uint32_t last_counter) {
  Health s{};
  std::uint64_t sum = 0, nsat = 0, ndark = 0, grad = 0;
  for (int y = 0; y < f.h; y += 2) {                 // every other row: half the cost, same verdict
    const std::uint8_t* row = f.px + static_cast<std::size_t>(y) * f.w;
    for (int x = 1; x < f.w; ++x) {
      const int v = row[x];
      sum += v; nsat += v >= 250; ndark += v <= 8;
      grad += static_cast<std::uint64_t>(std::abs(v - row[x - 1]));   // edges vanish under blur and fog
    }
  }
  const float n = static_cast<float>(((f.h + 1) / 2) * (f.w - 1));
  s.mean = sum / n;  s.sat = nsat / n;  s.dark = ndark / n;  s.sharp = grad / n;
  s.age_us = now_us - f.stamp_us;                     // how old is what we are about to trust?
  s.repeated = (f.counter == last_counter);           // the same frame twice: the pipe is stuck
  return s;
}

struct HealthLimits { float sat_max, dark_max, sharp_min; std::int64_t age_max_us; };
inline Reason judge(const Health& s, const HealthLimits& L) {
  if (s.repeated || s.age_us > L.age_max_us) return Reason::StaleInput;  // cheapest, most certain
  if (s.sat > L.sat_max || s.dark > L.dark_max) return Reason::BadExposure;
  if (s.sharp < L.sharp_min) return Reason::Blocked;                      // blur, mud, fog: no edges
  return Reason::Ok;
}

Note the order in judge. The stale check comes first, because it is the cheapest and the most certain. A repeated counter is not a statistical guess; it is a fact.

Calibration drift

One more input fault is slow. The camera is mounted on a bracket. Heat, vibration or a knock can turn it by a fraction of a degree. The image looks perfect, but every 3D position the model reports is slightly rotated.

0.5° of yaw error at 50 m: 50 × tan(0.5°) = 0.44 m sideways  ·  at 100 m: 0.87 m, half a lane

No single frame reveals this. A monitor finds it by comparing the camera against another sensor over many objects, as in Chapter 4, and watching the average offset. The calibration lesson covers how the sensors are aligned in the first place.

Where it goes wrong

Failure mode: the limits are tuned on one camera. A second supplier's camera has a different gain curve. Its normal night images fall over the dark limit, and the input monitor reports "unhealthy" every evening.

How to diagnose it: plot each statistic's distribution per camera model, per time of day, from normal drives. The limits must sit outside the normal spread of every camera type you ship. Store limits per camera model, and log the raw statistics with every flag so you can tell a bad camera from a bad limit.

An interviewer asks: "Every frame from the camera is sharp and well exposed, yet the car fails to brake for a stopping car. Which input health check would have helped?"

Chapter 7

When the scene is unlike training

Learn what a confidence score is, how to calibrate it, and how little it can tell you about a new kind of scene

A detector trained on dry daytime roads meets its first snowstorm. Lane lines vanish. Cars wear white roofs. A plough with flashing lights fills the lane. The detector still outputs boxes, some with confidence 0.95. Should you believe a 0.95?

Every chapter so far checked the output against the world. This one asks a different question: can the model tell us when it is out of its depth? The honest answer is "a little, sometimes". This chapter shows what that little is worth.

Confidence is not probability

The confidence a detector prints is a number between 0 and 1 that the network learned to produce. It is tempting to read 0.9 as "right 9 times in 10". That reading is only true if the model is calibrated: among all detections with confidence near 0.9, about 90% are correct. Many modern networks are not. They tend to be overconfident: their 0.9s are right less often than 90% of the time.

You check calibration with a reliability diagram. Sort held-out detections into bins by confidence: 0.0 to 0.1, 0.1 to 0.2, and so on. In each bin, compare the average confidence with the share that were actually correct. A calibrated model's bars sit on the diagonal.

ECE = Σb (nb / N) · | accb − confb |
ECE
expected calibration error: the average gap between confidence and accuracy
b
one confidence bin
nb
how many detections fell in that bin
N
all detections in the test set
accb
the share of that bin that was correct
confb
the average confidence in that bin

one bin: 100 detections, average confidence 0.90, 72 correct: gap = |0.72 − 0.90| = 0.18, weighted by its share of N

Temperature scaling

A simple fix often helps a lot. Before the final squashing function (a sigmoid for one class, a softmax for many), divide the network's raw scores, its logits, by one number T, the temperature. T > 1 softens over-confident outputs; T is fitted once on held-out data. This is temperature scaling. It does not change which class wins, only how sure the model claims to be.

one class, logit 3.0: sigmoid(3.0) = 0.953  ·  with T = 2: sigmoid(1.5) = 0.818

three classes, logits [3, 1, 0]: e³ / (e³ + e + 1) = 20.1 / 23.8 = 0.844  ·  T = 2: e1.5 / (e1.5 + e0.5 + 1) = 4.48 / 7.13 = 0.629

Is 0.9 really 90%?

Each bar is one confidence bin: its height is the share that was correct. The diagonal is perfect calibration; warm shading is the gap. Move the temperature, or press Fit T on day data. Then switch to night with the same T.

1.00

Synthetic scores, 6,000 per set, from the recipe in the Python below: the model's logits are twice what they should be. At night the true accuracy drops but the model's scores do not drop as much. This illustrates the effect; it is not a measurement of any real detector.

Fit T on day data and the day bars land on the diagonal. Now switch to night without refitting. The gap comes back. Calibration is a property of a model and a data distribution. Fitting it on one distribution says little about another.

import numpy as np

def ece(conf, correct, bins=10):
    """Expected calibration error: the gap between confidence and accuracy, per bin, weighted."""
    edges = np.linspace(0, 1, bins + 1)
    total = 0.0
    for lo, hi in zip(edges[:-1], edges[1:]):
        m = (conf > lo) & (conf <= hi)
        if m.any():
            total += m.mean() * abs(conf[m].mean() - correct[m].mean())
    return total

def fit_temperature(logits, correct):
    """Temperature scaling for a binary score: one number T, fitted on held-out data."""
    best = (1e9, 1.0)
    for T in np.linspace(0.5, 5.0, 451):
        p = 1 / (1 + np.exp(-logits / T))
        nll = -np.mean(correct * np.log(p + 1e-12) + (1 - correct) * np.log(1 - p + 1e-12))
        best = min(best, (nll, T))
    return best[1]

rng = np.random.default_rng(0)
true_logit = rng.normal(1.5, 1.2, 20000)              # how sure the model SHOULD be
correct = (rng.random(20000) < 1 / (1 + np.exp(-true_logit))).astype(float)
logits = 2.0 * true_logit                              # an overconfident model: logits too big
conf = 1 / (1 + np.exp(-logits))

T = fit_temperature(logits[:10000], correct[:10000])   # fit on one half ...
cal = 1 / (1 + np.exp(-logits[10000:] / T))            # ... judge on the other half
print("T =", round(T, 2))
print("ECE before:", round(ece(conf[10000:], correct[10000:]), 3))
print("ECE after: ", round(ece(cal, correct[10000:]), 3))

On this synthetic data the fit gives T = 1.92, and the calibration error falls from 0.10 to 0.012 on the half that was not used for fitting. Real detectors need more care: calibrate per class, and check per condition (day, night, rain), because one T rarely fits all.

Out-of-distribution signals

A scene is out of distribution (OOD) when it differs from anything in the training data. Examples: snow for a model trained on summer, a new kind of vehicle, a camera with a cracked lens. A model there can be confidently wrong. Research has proposed several signals that tend to be different on such inputs. Here are the ones you should know by name.

How to use weak evidence

So what does an onboard lead do with these scores? Not "if OOD score > t then emergency stop". Instead, treat them as one input among many.

The uncertainty lesson goes deeper on where a model's doubt comes from, and the calibration lecture treats calibration for language models, where the same ideas apply.

Where it goes wrong

Failure mode: the threshold was tuned on the wrong shift. A team picks an OOD threshold that flags their night test set well. In the field, the first heavy rain produces scores just below it, and nothing is flagged. The score learned to separate day from night, not normal from risky.

How to diagnose it: evaluate the score on several kinds of shift that were not used to tune it, and report results per shift. If it only works on the shift it was tuned on, treat it as a logging signal, not a safety signal.

An interviewer asks: "We applied temperature scaling and our ECE on the validation set is now tiny. Can the planner treat confidence as a probability in the field?"

Chapter 8

Thresholds are a trade

Choose where to draw the line between false alarms and missed faults, from costs, and stop one bad frame from flipping the system

Go back to the hero and slide the threshold to 1σ. The monitors start flagging good cars. Slide it to 12σ. The ghost slips through when a real car's radar return happens to sit nearby. Somewhere between, there is a best setting, and it is not obvious where.

Every monitor reduces to the same shape. It computes a score for each output, such as the innovation z or the distance to the nearest radar return. Good outputs mostly have low scores. Faulty outputs mostly have high scores. The two groups overlap, and the threshold k decides which side of the overlap you lose.

Two rates describe a threshold. The true positive rate (TPR) is the share of faults flagged. The false positive rate (FPR) is the share of good outputs flagged. Sweep k from low to high and plot TPR against FPR: that curve is the ROC curve. Each point on it is one possible operating point.

Draw the line

Top left: scores of good outputs (green) and faults (yellow). Top right: the ROC curve and your point. Bottom: expected cost per hour against threshold, with the best point marked. Drag the threshold, then change the costs.

3.00 σ
6.0 σ
1,000×
1,000

Good scores are the size of a standard normal (folded at zero); fault scores are normal with mean "fault strength" and standard deviation 2. 36,000 frames an hour. Costs are relative units: one false alarm costs 1. Illustrative.

Choose the operating point from costs

A false alarm and a missed fault do not cost the same. A false alarm might mean a gentle slowdown. A missed ghost might mean a hard phantom brake; a missed real object might mean a crash. So you choose k to minimise the expected cost per hour:

C(k) = cFA · Ngood · FPR(k) + cmiss · Nfault · (1 − TPR(k))
C(k)
the expected cost per hour at threshold k
k
the threshold, in standard deviations of normal noise
cFA
the cost of one false alarm
Ngood
good outputs per hour
FPR(k)
the share of good outputs flagged
cmiss
the cost of one missed fault
Nfault
faulty outputs per hour
TPR(k)
the share of faults flagged

Worked, with the device's defaults: 36,000 frames an hour, 1 in 1,000 faulty, so Nfault = 36 and Ngood = 35,964. A miss costs 1,000 times a false alarm.

kFPRTPRfalse alarms / hmisses / hcost / h
2.51.24%96.0%4471.44447 + 1,440 ≈ 1,890
3.00.27%93.3%972.4197 + 2,410 ≈ 2,500
4.00.006%84.1%2.35.712.3 + 5,710 ≈ 5,710

The best single threshold is near k = 2.4, and it still costs about 450 false alarms an hour. That is far too many to live with. A single frame-by-frame threshold cannot win here, because the two score groups overlap too much. The fix is to use more than one frame.

import math
Phi=lambda z:0.5*(1+math.erf(z/math.sqrt(2)))
frames=36000; prior=1e-3
nf=frames*prior; ng=frames-nf
c_fa=1.0; c_miss=1000.0
best=None
for k in [1,1.5,2,2.5,3,3.5,4,4.5,5,6]:
    fpr=2*(1-Phi(k)); tpr=1-Phi((k-6)/2)
    fa=fpr*ng; miss=(1-tpr)*nf; cost=c_fa*fa+c_miss*miss
    print(k, round(fpr,5), round(tpr,4), round(fa,1), round(miss,2), round(cost,1))
# fine search
ks=[i/100 for i in range(50,800)]
cs=[(c_fa*2*(1-Phi(k))*ng + c_miss*Phi((k-6)/2)*nf,k) for k in ks]
print(min(cs))
# debounce 3 in a row false
print('3 in row at fpr .01:', 0.01**3*ng)

Debouncing and hysteresis

Most real faults last more than one frame; most noise does not repeat. So require the score to cross the threshold in several frames in a row before the flag goes up. That is debouncing. If false crossings are independent from frame to frame, two in a row happen with probability FPR².

k = 2.5, two frames in a row: 0.0124² × 35,964 = 5.5 false alarms / h  ·  a fault lasting 2+ frames: 0.960² = 92% caught, 0.1 s later

From 447 false alarms an hour to about 5, for 0.1 s of delay. That is usually a good trade, and it is why the hero's radar check waits three silent frames on established objects.

The second trick is hysteresis: two thresholds instead of one. The flag goes up when the score rises above kon, and comes down only when it falls below a lower koff. A score hovering near one threshold no longer makes the flag flicker. Combine both: quick to worry, slow to relax.

Stop the flicker

A monitor score over 12 s. A real fault runs from 5 s to 8 s (yellow band). The strip below shows when the flag is up. Count the switches and the delay. Change the rule.

3.0 σ
1.8 σ
3

Seeded toy score at 10 Hz. "Off below" only matters with hysteresis; "frames in a row" only matters with debouncing. The fault's score dips during its middle second, as real faults often do.

Here is the latch in C++. It reports edges, the frames where the state changes, so the log records events, not a stream of levels.

// Debounce plus hysteresis: one bad frame must not flip the whole system.
#include <cstdint>

struct Latch {
  float on_at, off_at;        // two thresholds: on_at > off_at leaves a dead band between them
  int need_on, need_off;      // frames in a row before a change is believed
  bool on = false;
  int streak = 0;

  // Returns true only on the frame the state changes, so callers log edges, not levels.
  bool update(float score) {
    const bool want = on ? !(score < off_at) : (score > on_at);
    if (want == on) { streak = 0; return false; }   // no pressure to change: reset the count
    if (++streak < (on ? need_off : need_on)) return false;
    on = want; streak = 0;
    return true;
  }
};

// Typical use: a monitor score in standard deviations, 10 Hz cycle.
//   Latch flag{4.0f, 2.5f, 2, 10};
//   2 frames above 4.0 sigma to raise the flag (0.2 s),
//   10 frames below 2.5 sigma to clear it (1.0 s): quick to worry, slow to relax.
inline int count_switches(const float* s, int n, Latch l) {
  int edges = 0;
  for (int i = 0; i < n; ++i) edges += l.update(s[i]) ? 1 : 0;
  return edges;
}

Where it goes wrong

Failure mode: the debounce hides short, dangerous faults. A three-frame debounce stops flicker. It also lets through any fault that lasts two frames. A ghost that appears for 0.2 s in front of the car can still cause a short hard brake.

How to diagnose it: plot detection rate against fault duration from fault-injection tests (Chapter 10). A cliff at the debounce length is the signature. Fix it by debouncing only actions that are cheap to delay, and by making the planner itself robust to one-frame objects, for example by requiring persistence before hard braking.

An interviewer asks: "Our monitor's best single threshold still gives hundreds of false alarms an hour. What do you change?"

Chapter 9

What a monitor may do

Turn a flag into a safe, logged action, from dropping one box to stopping the car, and never silently fix the output

A monitor flags the ghost. Now what? Delete the box? Brake? Tell the driver? Switch the camera off? The flag is only half the job. The other half is what the system does with it, and that must be designed as carefully as the check.

A ladder of actions

Actions differ in how much of the system they touch. Choose the smallest action that removes the risk.

  1. Flag: mark the output as suspect and pass it on. Downstream code decides.
  2. Down-weight: keep the object but trust it less, for example by requiring more evidence before braking hard for it.
  3. Drop one object: remove one implausible box. The rest of the sensor's output is still used.
  4. Sensor fallback: stop using one sensor for a region or for everything, and use the others.
  5. Degrade the function: lower the speed, increase the following gap, disable lane changes.
  6. Minimal risk manoeuvre: bring the vehicle to a safe stop, in lane or on the shoulder, and hand over to a person if there is one.

Never silently fix the output

It is tempting to "repair" a bad detection: clip the 4.4 m wide car to 2.2 m, or move the teleported box back to where the track said it should be. Do not. A repaired output looks healthy to everything downstream. The planner cannot tell an observed car from a guessed one. The logs show no fault. And the repair rule can itself be wrong.

Instead, keep the original, attach the verdict and its reason, and let the consumer choose. A coasting track is fine because it is labelled as coasting. The difference between a prediction and a fabrication is the label.

Degraded modes as a state machine

System-level actions are best written as a small state machine. Each state is a mode the vehicle can be in. Each arrow is a monitor event. The safety-critical architecture lesson treats this machine as a safety requirement; here we feed it from perception monitors.

From flag to mode

The vehicle starts in Nominal. Fire monitor events and watch the mode, the speed cap and the log. Moving down is quick; moving back up needs a clean period.

An illustrative machine with four modes. A real one has more inputs (driver state, map, weather) and is derived from the hazard analysis. Speed caps are worked out below for a 20 m/s road.

How fast may a degraded car go? A worked number

The camera is out, and the car falls back to radar. Suppose the radar alone can be trusted to find a stopped object 25 m ahead (an illustrative figure; radars often have trouble with stationary objects). The car must be able to stop within that distance. With a system reaction time t of 0.5 s and a firm braking rate a of 6 m/s²:

d = v t + v² / (2 a)   ⇒   v = a ( −t + √( t² + 2 d / a ) )
d
the distance the fallback sensor can be trusted to see, in metres
v
the highest speed that still stops within d
t
the reaction time of the whole system, before braking starts
a
the braking rate the car can count on

d = 25 m: v = 6 × (−0.5 + √(0.25 + 8.33)) = 6 × (−0.5 + 2.93) = 14.6 m/s, about 53 km/h

So the degraded mode caps the speed at about 15 m/s. If the trusted range shrinks to 15 m, the cap falls to 6 × (−0.5 + √5.25) = 10.7 m/s. The cap follows from the fallback's abilities, not from a guess.

Here is the action table and the log in C++. One table maps every reason to one action. An unknown reason maps to the safest action. And every decision goes into a fixed ring buffer that a slower task copies to storage.

// What a monitor may do: map each reason to an action, and log every decision.
#include <array>
#include <cstdint>

enum class Action : std::uint8_t { None, Flag, DropObject, Downweight, SensorFallback, SpeedCap, MinimalRisk };

// One table, reviewed like a requirement. No monitor edits the detection itself.
constexpr Action action_for(Reason r) {
  switch (r) {
    case Reason::Ok:               return Action::None;
    case Reason::Unconfirmed:      return Action::Flag;          // hold, do not delete
    case Reason::SizeImplausible:
    case Reason::SpeedImplausible:
    case Reason::OffGround:
    case Reason::Teleport:
    case Reason::GeometryMismatch: return Action::DropObject;    // one object, not the sensor
    case Reason::NoRadarSupport:   return Action::Downweight;
    case Reason::CameraMiss:       return Action::SensorFallback; // use the radar track there
    case Reason::StaleInput:
    case Reason::BadExposure:
    case Reason::Blocked:          return Action::SpeedCap;      // the whole camera is suspect
  }
  return Action::MinimalRisk;                                     // unknown code: safest choice
}

// A fixed ring buffer of records, copied to storage by a slower task.
struct LogRec { std::uint32_t cycle; std::uint16_t object_id; Reason reason; Action action; float score; };
template <std::size_t N>
struct Ring {
  std::array<LogRec, N> buf{};
  std::uint32_t head = 0, lost = 0;      // lost counts records the writer had to overwrite
  std::uint32_t unread = 0;
  void put(const LogRec& r) {
    buf[head % N] = r; ++head;
    if (unread == N) ++lost; else ++unread;
  }
};

Log everything, for later

Monitors are also the best data source a perception team has. Every flag is a candidate model error, with the frame number, the reason, the score and the action. Engineers replay the logged sensor data around each flag, label what really happened, and feed the hard cases back into training. A monitor that flags but does not log wastes half its value.

Where it goes wrong

Failure mode: mode flapping. The camera health flag flickers at dusk. The car drops into Degraded, recovers, drops again, five times a minute. Each switch changes the speed cap. Passengers feel the car surge and slow.

How to diagnose it: count mode transitions per hour from the log, and look at the time between them. Short gaps mean the return path is too easy. Fix it with the hysteresis from Chapter 8 on the way back up: a clean period of seconds, not frames, before leaving a degraded mode.

An interviewer asks: "Your physics monitor sees a car box that is 4.4 m wide. A colleague proposes clipping the width to 2.2 m and passing it on. What do you say?"

Chapter 10

Testing a monitor

Make the faults happen on purpose, measure how fast each monitor catches them, and test the monitor's own failures

A monitor that has never seen a fault has never been tested. Real faults are rare: Chapter 0 showed a good detector might be wrong once every few hours. You cannot wait for them. You have to make them.

Three ways to make faults

A fourth technique tests the tests. Mutation testing changes the monitor's own code, for example by flipping a > to >= or deleting a check, and runs the test suite. If every test still passes, the suite cannot see that code. Good suites "kill" nearly every such mutant.

What to measure

For each fault type, at each strength, three numbers matter.

  1. Detection rate: the share of injected faults that any monitor flags.
  2. Detection time: the frames from the start of the fault to the first flag. It must fit inside the time the downstream function can tolerate.
  3. False alarm rate: flags per hour on clean drives. Measure it on many hours of normal driving, not on the fault cases.

Run the campaign

Each row is a fault type, injected 40 times into the hero's toy scene at random moments. Each column is one monitor, judged alone; the last column is any monitor. A cell shows the share caught within 1 s, and its shade is the same number. Pick a strength and a threshold, then run.

4.0 σ

Mild, typical and severe change the size of each fault. Ghost length 2, 5 or 10 frames. Teleport: 1.5, 4 or 8 m. Extra width: 0.4, 1.5 or 3 m. A miss: 3, 8 or 20 frames. A freeze: 2, 6 or 20 frames. Temporal counts a ghost as caught if it never reached the planner. Same toy engine as the hero.

Read the matrix by rows and by columns. Each row should have at least one strong cell: some monitor covers that fault. Rows with two strong cells have redundancy: one monitor can fail and the fault is still caught. Columns show what each monitor is for. Set the strength to mild: the weak cells show which faults slip under the noise.

How many tests are enough? A worked number

You inject n faults and the monitor catches every one. That does not prove the miss rate is zero. A useful rule, the rule of three, says that with zero failures in n independent trials, the true failure rate is below about 3 / n with 95% confidence.

300 injected ghosts, all caught: miss rate < 3 / 300 = 1% (95%)  ·  to claim < 0.1%: 3,000 injections with no miss

no false alarm in 1,000 h of replay: rate < 3 / 1,000 = 0.003 per hour (95%)

The same rule shows why replay data matters so much. A false alarm rate is a claim about normal driving, so it needs a large volume of normal driving to back it.

Here is a deterministic fault injector in C++. The random generator is a tiny seeded xorshift, so the same seed produces the same faults on every machine and every run. A failing test can be replayed exactly.

// Fault injection: mutate a recorded detection list, deterministically, then
// check that the right monitor fires within its time budget.
#include <cstdint>

struct Det { std::uint16_t id; float x, y, len, wid, conf; };
template <int N> struct DetList { Det d[N]; int n = 0; };

enum class Fault : std::uint8_t { Ghost, Teleport, Size, Miss, Freeze };

struct Rng {                                      // tiny, seeded, the same on every machine
  std::uint32_t s;
  float uni() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return (s >> 8) * (1.0f / 16777216.0f); }
};

template <int N>
void inject(DetList<N>& out, const DetList<N>& last_frame, Fault f, float mag, Rng& r) {
  switch (f) {
    case Fault::Ghost:                            // a confident object where nothing is
      if (out.n < N) out.d[out.n++] = Det{900, 12.f + 25.f * r.uni(), 0.3f, 4.4f, 1.8f, 0.91f};
      break;
    case Fault::Teleport:                         // one object jumps by mag metres
      if (out.n > 0) { out.d[0].x -= mag; out.d[0].y -= 0.5f * mag; }
      break;
    case Fault::Size:                             // one object grows to an impossible width
      if (out.n > 0) out.d[0].wid += mag;
      break;
    case Fault::Miss:                             // one real object vanishes
      if (out.n > 0) { out.d[0] = out.d[out.n - 1]; --out.n; }
      break;
    case Fault::Freeze:                           // the whole list repeats, bit for bit
      out = last_frame;
      break;
  }
}

// A test checks two numbers per fault: detected at all, and how fast.
struct Outcome { bool detected; int frames_to_flag; };
inline bool passes(const Outcome& o, int budget_frames) {
  return o.detected && o.frames_to_flag <= budget_frames;
}

The monitor's own failure modes

A monitor is software, so it fails too. Test these on purpose.

Where it goes wrong

Failure mode: the test passes because the fault is too easy. Every injected ghost is placed in an empty lane, far from real objects. The radar check catches all of them. In the field, a ghost next to a real car borrows that car's radar return and passes.

How to diagnose it: sweep fault strength and placement, not just fault type, and plot detection rate against each. A campaign should include the mild, nasty cases. In the device, compare typical and mild ghosts with a loose threshold.

An interviewer asks: "You injected 300 teleport faults and caught all 300. What can you claim?"

Chapter 11

The monitor bench

Drive half an hour of faults through every monitor at once, tune each threshold, and find the settings that break

Everything so far, at once. The bench drives the hero's toy scene for 30 simulated minutes. Faults arrive at random, at the rate you choose, drawn from the types you switch on. Every monitor runs with its own threshold. The results panel counts what a real validation report would count.

Break the monitors

Top: the first three minutes. Each fault is a yellow bar; each flag is a tick, warm when it caught a fault and red when it was a false alarm. Below: detection rate per fault type. Set the monitors, then drive.

3.0
1.0×
4.0 σ
4.0 σ
4.0 σ
4.0 σ
100×
–faults caught
–mean time to flag
–false alarms per hour
–bad frames to planner per hour
–cost per hour

Same toy engine and scene as the hero, without the braking lead car. A "bad frame to the planner" is a frame in which the planner saw a faulty box, or lost a real object with no stand-in. Cost: a false alarm costs 1, a bad frame costs the "miss costs" value. The monitors assume the detector's normal noise (1.0×); raising the noise without retuning them shows what a model update can do. Illustrative.

Things to try

  1. Turn every monitor off. Every fault reaches the planner. Note the bad frames per hour: that is the model's raw error, exposed.
  2. Turn on one monitor at a time. Watch which rows of the detection bars fill. No single monitor covers every fault type. That is the case for a family of monitors.
  3. Set every threshold to 1σ. Detection nears 100% and false alarms explode into the thousands per hour. Then set them all to 12σ and watch faults slip through.
  4. Raise the detector noise to 2× without touching the thresholds. False alarms rise sharply. This is what happens when a new model ships with different noise and nobody retunes the monitors.
  5. Find the cheapest settings. Move the four thresholds one at a time and watch the cost. The best setting is different for each monitor, because their scores mean different things.

One honest caveat about this bench. Its faults come from a list we wrote, at strengths we chose. A real bench replays thousands of hours of recorded drives, with faults injected into real model outputs and real faults labelled from the fleet. The method is the same; the scale and the realism are not.

Where it goes wrong

Failure mode: the bench rewards the wrong thing. A team tunes for detection rate alone. Thresholds creep down, detection reaches 99.8%, and nobody watches false alarms per hour until the first fleet week produces thousands of needless slowdowns.

How to diagnose it: always report detection rate, detection time and false alarm rate together, with costs, as the results panel does. A release gate should fail if any one of them gets worse beyond an agreed margin.

An interviewer asks: "A new perception model ships, nobody retunes the monitors, and false alarms jump tenfold. What happened?"

Chapter 12

Interview arsenal

Gather the numbers, the design frames, the drills and the debugging stories in one place

Here is the lesson in one paragraph. A learned detector is right almost always and wrong without warning. A runtime monitor is a simple, independent checker beside it, in the Simplex spirit: the doer does the work, the checker judges it, and a fallback takes over when the checker objects. Monitors check outputs against physics, time, other sensors and geometry, and they check the input's health.

Confidence and OOD scores help a little, and only where calibration still holds. Every monitor is a threshold on a score, so it trades false alarms against missed faults; debouncing and hysteresis use time to escape that trade. Flags turn into labelled, logged actions, never silent repairs. And monitors are proved by injecting faults and measuring detection rate, detection time and false alarms per hour.

From symptom to cause

Pick a symptom from a field report. The pipeline lights the stages to check first, in order, and the read-out says what to look at.

A study aid: real incidents can have several causes. Always confirm with a replay of the logged data.

Cheat sheet

IdeaOne lineNumber to remember
Why monitorcount wrong frames, not percentages1 in 1,000 at 10 Hz = 36 per hour
Simplex switchhand over while the fallback can still recovermargin = v td + v²/2a: 0.24 m at 0.8 m/s
Acceleration checksecond difference amplifies noise by √6/Δt²0.2 m noise: 49 m/s² at 0.1 s, 2 m/s² at 0.5 s
Persistencehold a newcomer until M frames in a rowflicker at 1%: 0.01³ = 10−6; costs 0.2 s
Innovation gatez = innovation / expected spread6 m jump, σ 0.35 m: z = 17
Expected detectionsilence counts only where the sensor can seeghost odds 1% → 9% (1 frame) → 91% (3 frames)
Pinhole checkZ = fH/h and Z = f hc/(vb − v0)50 px car: 28 to 32 m; 47 px below horizon: 29.8 m
Freshnessrepeated counter or old timestamp30 Hz camera, 100 ms limit = 2 m at 20 m/s
Calibration driftan angle error grows with range0.5° at 50 m = 0.44 m
Calibration (ECE)confidence should match accuracy, per conditionsynthetic: T = 1.92, ECE 0.10 → 0.012
Operating pointminimise cFA·FA + cmiss·missesk 2.5: 447 FA/h; 2 in a row: 5.5 FA/h
Degraded speed capstop within what the fallback can see25 m, 0.5 s, 6 m/s²: 14.6 m/s
Test volumezero failures in n trials: rate < 3/n300 caught of 300: miss rate < 1%

Three system design prompts

1. Design the runtime monitor layer for a camera detector in a highway assistance system

One front camera network and one front radar, 20 Hz (illustrative), output feeds adaptive cruise and automatic emergency braking.

  1. Clarify: which faults matter for each function. For braking: phantom objects in the path (false braking) and missed objects in the path (no braking). Ask the time each function can tolerate a bad input.
  2. Input health: frame counter, capture timestamp age, exposure and sharpness per tile, camera to radar alignment over time.
  3. Output checks: physics table per class, ground contact, persistence for newcomers, innovation gate against the tracker, radar agreement with expected detection.
  4. Actions: drop single objects; down-weight unsupported ones; camera fallback to radar with a speed cap; a minimal risk manoeuvre if both are unhealthy. Hysteresis on every mode change.
  5. Real time: fixed-capacity result lists, bounded loops over a capped object count, a worst-case time budget, a watchdog on the monitor itself.
  6. Validation: fault injection per type and strength, replay of labelled fleet flags, detection rate, detection time and false alarms per hour as release gates.

2. Design input health monitoring for a robot with eight cameras

  1. Per camera, every frame: counter and age, exposure and sharpness on a tile grid, cheap enough to run on all eight.
  2. Across cameras: overlapping views must agree on shared objects; a camera that disagrees with both neighbours is the suspect.
  3. Slow drifts: track alignment against lidar or the other cameras over minutes, with a separate, slower alarm.
  4. Actions: map each camera to the regions it covers; a sick camera shrinks the safe region, which caps speed or blocks some manoeuvres, rather than stopping the robot outright.
  5. Limits: per camera model and per lighting condition, learned from normal drives, logged with raw statistics on every flag.

3. The ML team ships a better detector and your monitors' false alarms double. What do you do?

  1. Measure first: replay the same logs through old and new models; compare each monitor's score distribution on clean data.
  2. Find the cause: often the new model's box noise or confidence scale changed, so the monitors' assumed σ is now wrong.
  3. Retune with data: re-estimate noise per class and range from the new model; re-run fault injection to confirm coverage holds.
  4. Fix the process: make monitor false alarm rate and detection rate part of the model's release gate, so the next update cannot ship without them.

Three coding drills

  1. Implied speed. Write a function that returns the speed between two stamped positions, and refuses when the time step is zero, negative, NaN or too short. Then a speed check that gives no verdict, not a pass, without enough baseline.
  2. Latch. Implement debounce plus hysteresis for a monitor score, returning true only on edges. Test: a single spike, a dip inside a fault, and a score hovering at the threshold.
  3. Persistence table. A fixed-capacity table of up to 64 tracks keyed by ID, each with an 8-bit history. No heap. Decide and test what happens when a 65th ID arrives.

Here is one answer to the first drill. The point an interviewer looks for is that "cannot tell" is never treated as "fine".

// Drill answer: implied speed between two detections of one track, safely.
#include <cmath>
#include <cstdint>

struct Stamped { float x, y; std::int64_t t_us; };

// Returns false when the question cannot be answered; the caller must not treat that as "fine".
inline bool implied_speed(const Stamped& a, const Stamped& b, float min_dt_s, float& v_out) {
  const float dt = static_cast<float>(b.t_us - a.t_us) * 1e-6f;
  if (!(dt >= min_dt_s)) return false;           // zero, negative, NaN, or too short to trust
  const float dx = b.x - a.x, dy = b.y - a.y;
  if (!std::isfinite(dx) || !std::isfinite(dy)) return false;
  v_out = std::sqrt(dx * dx + dy * dy) / dt;
  return true;
}

// Speed check with a wide enough baseline: noise in v falls as 1/dt.
inline Reason speed_check(const Stamped& a, const Stamped& b, float v_max, float v_slack) {
  float v = 0.f;
  if (!implied_speed(a, b, 0.2f, v)) return Reason::Ok;   // not enough baseline yet: no verdict
  return v > v_max + v_slack ? Reason::SpeedImplausible : Reason::Ok;
}

// Tests:
//   a {10.0, 0, 0}, b {10.3, 0, 300000}    -> 1.0 m/s, Ok for a pedestrian (10 m/s limit)
//   a {10.0, 0, 0}, b {20.0, 0, 300000}    -> 33 m/s, SpeedImplausible for a pedestrian
//   a and b with the same stamp             -> no verdict, and never a divide by zero

Three debugging scenarios

  1. "Phantom braking, always at the same bridge." The camera network sees the bridge's shadow as an object, and the radar's return from the bridge itself sits close enough to "agree". Check: map the flags; log the radar return's height if the radar measures elevation. Fix: an elevation or map check on agreement, and a geometry check on the camera box's ground contact.
  2. "After the model update, false alarms doubled." The new model's position noise is larger at long range; the temporal gate still assumes the old σ. Check: innovation z distributions before and after, per range band. Fix: re-estimate σ per class and range; add monitor metrics to the model's release gate.
  3. "A frozen camera went unnoticed for 300 ms." The driver re-sent the last frame with a fresh timestamp, so the age check saw young frames, and nobody checked the counter. Check: capture-time stamps against receive-time stamps in the log. Fix: stamp at capture in hardware, check the frame counter, and test by freezing the driver on purpose.

Classical checks and learned signals

Classical monitors (Chapters 2 to 6)Learned signals (Chapter 7)
What they testrules the world always obeys: physics, time, geometry, other sensors, input qualityhow unusual the input or the model's state looks
Can you verify them?yes: short code, explicit limits, reviewablehard: they are models too
On a novel scenestill valid; physics holds in snowmay fail exactly where they are needed
Blind spota lie that obeys every rulea confident error on an ordinary-looking input
Best usehard flags and actionscaution, extra agreement, data mining

Where the field sits, briefly and honestly. The Simplex architecture gave the doer and checker pattern its classic form. Responsibility-Sensitive Safety (RSS) proposes formal rules for safe distances that a checker can enforce on a planner. The SOTIF standard (ISO 21448) addresses hazards from a system that works as designed but is not good enough for the situation. That is exactly the learned-perception problem. ISO 26262 covers faults in the electronics and software. Runtime monitoring of neural networks, OOD detection and calibration remain active research, with no method that covers every case.

Reading list

Keep going on this site

The takeaway. Trust a learned model through a checker you can read. Give the checker rules the world always obeys, make it independent of the model, choose its thresholds from costs, let time settle doubtful frames, turn every flag into a labelled and logged action, and prove it all with injected faults.

Now press Present or Teach and explain, from memory, why the radar check catches a persistent ghost that temporal consistency lets through, and why the radar check needs expected detection. Then go back to the road, set the threshold to 12σ with only the radar check on, and replay the ghost until a nearby car vouches for it.

An interviewer asks: "In one sentence, what makes a runtime monitor for a learned perception model trustworthy?"
Runtime Monitors for ML Perception
Multi-target tracking · Safety-critical architecture · Back to Gleams