Want a quick email when a new article is published? Subscribe

Ninety-nine numbers learn to fly: the whole project, in code, with the machine learning explained

25 min read • 30 Nov 2026
aimachine learningneuroevolutionaviation
Executive summary

This is the whole project in code, in the order it happened, with each machine learning idea explained for a software engineer meeting it for the first time. Three small neural networks (99 to 195 numbers each) learned to take off, fly a circuit and land a light aircraft in my simulator, BigSkySim, then passed ten of ten flights on the real, browser-hosted simulator.

  • A pilot is a function. Its weights are a flat array; flying is a forward pass from a pilot’s-eye view (rounded instruments, distances, a radio-style position report) to stick, rudder, throttle and brake.

  • Learning without gradients. Neuroevolution: score a thousand random networks, keep the best, add Gaussian noise to copies, repeat. The breeding step is a few lines and never changed.

  • Measure before you replace. A linear stand-in model of the plane made fast practice possible but cost the pilots about five points. Profiling showed the 65 ms per step was almost all transport, with the physics taking microseconds; the JavaScript physics core runs in Node, thousands of worlds at once, 300 hours of flying in about four and a half seconds, deterministically.

  • The fitness function is the spec. The take-off score’s code is a history of loopholes found and closed. Points shifted results, and a habit that points left alone needed a terminating rule; an all-or-nothing rule leaves a flat landscape with nothing to climb, so it needed partial credit and a warm start.

  • Composition and distribution shift. Three learned pilots plus hand-written glue. The landing pilot failed one in six after a real circuit because handovers looked nothing like its training starts; replaying real handovers fixed it (194 of 200).

  • Train on production information. The navigator was rebuilt on the position report a real pilot gets: 489 of 500 circuits, against 488 with exact position.

  • Variance and the winner’s curse. A hundred test flights can’t separate a 3% crasher from a 0.5% one; selection on a thousand, and a fresh final comparison, fixed it.

Here is the entire brain of the pilot that learned to take off a light aircraft in gusty crosswinds, from standing still on the runway to 500 feet:

def think(genomes, inputs):
    w1, b1, w2, b2 = _unpack(genomes)
    hidden = np.tanh(np.einsum("pi,pih->ph", inputs, w1) + b1)
    out = np.tanh(np.einsum("ph,pho->po", hidden, w2) + b2)
    return np.column_stack([50 * out[:, 0], 40 * out[:, 1], 80 * out[:, 2], np.full(len(out), 100.0)])

Four lines, and 99 numbers that nobody chose. Nothing in that function knows what a runway, a crosswind or a stall is. If you write software for a living and machine learning has always looked like someone else’s field, this piece walks through the whole project as it actually happened, in order, with the real code, and explains every machine learning idea it touches the first time it appears. Very little maths, and nothing you need to have read first.

The aeroplane lives in BigSkySim, a browser-based flight simulator of a small airfield that I built with the help of a series of AI coding models (the story of how is in Introduction). The machine learning project in this piece was built the same way: Claude Code, an AI coding assistant, wrote the code and ran the experiments, and I directed it, decided what counted as good flying, and argued with the results. Everything is in a notebook you can read at dada.ms/notebooks/learning-to-fly.html, and you can fly the simulator yourself at dada.ms/bigskysim/fly/.

A pilot is a function, and its weights are a flat array

Start with what that function does, because everything else is built on it.

A neural network, at this size, is a small calculation with a lot of adjustable knobs. Each pilot takes in 8 numbers (what it senses), and puts out 3 control positions. In between sit 8 “hidden” values. Each hidden value is a weighted sum of all 8 inputs, plus a constant (called a bias), passed through tanh, a function that squashes any number into the range -1 to +1. Each output is a weighted sum of the 8 hidden values plus its own bias, squashed the same way. Running inputs through to outputs is called the forward pass, and it is all a network ever does once it has been trained.

If spreadsheets help: imagine 8 input cells, 8 cells that each compute =TANH(SUMPRODUCT(inputs, my_weights) + my_bias), and 3 output cells that do the same over the middle row. The knobs are the weights and biases. Count them: 8 × 8 weights plus 8 biases into the hidden layer, 8 × 3 weights plus 3 biases out of it. That’s 64 + 8 + 24 + 3 = 99.

The take-off pilot's network Eight inputs on the left, eight hidden units in the middle and three outputs on the right, every input joined to every hidden unit and every hidden unit to every output. The lines are the final take-off pilot's own weights: blue positive, orange negative, thicker for larger. Distance from the centreline Turn needed to line up Airspeed Pitch (nose up or down) Bank (wings tilted) Climbing or sinking Height Rate of turn Stick forward or back Stick left or right Rudder pedals 8 inputs 8 hidden units 3 outputs
The whole take-off pilot. Each line is one of its sliders: 88 connections, plus one setting on each unit, 99 numbers in all. Drawn from the final pilot's real weights: blue lines push the same way as the input, orange the opposite way, thicker means stronger. The throttle isn't an output: it is always full.

The squashing matters. Without tanh, two layers of weighted sums collapse into one, and the pilot could only respond in straight-line proportion to what it sees. With it, the pilot can do things like “hold the elevator forward until the speed is right, then pull”.

The 99 numbers are stored as one flat array per pilot, which the code calls a genome, and _unpack slices it into the four matrices the forward pass needs. Treating the brain as a flat vector is what makes the learning method below so simple. To the learner, a pilot is just a row of 99 floats; it never needs to know which float connects to what.

genomes has a row per plane, and einsum (NumPy’s “multiply these arrays along these axes” notation, where p is the plane, i the input, h the hidden unit) computes a thousand different brains in one call. The outputs come out between -1 and +1 and get scaled into control positions, with the throttle fixed at full for a take-off.

The inputs need as much care as the outputs. Here are the take-off pilot’s eight senses, each scaled to roughly -1 to +1 so that no input dominates just because its units are big:

def sense(r):
    c = lambda name: r[:, COL[name]]
    return np.column_stack([
        np.nan_to_num(c("offset_m")) / 10,              # right of the centreline (0 when it can't be seen)
        wrap(RUNWAY_HDG - c("heading_deg")) / 20,       # how far to turn to the runway heading (+ = right)
        (c("airspeed_kt") - 55) / 20,                   # the gauge reads 0 below about 22 kt
        c("pitch_deg") / 10,
        c("bank_deg") / 20,
        c("vertical_speed_fpm") / 500,
        np.clip(c("altitude_ft") / 250, 0, 2),          # 0 on the ground
        c("turn_rate") / 3,
    ])

Choosing those eight is a human judgement, like choosing 8 hidden units rather than 4 or 40: more capacity, but a bigger space to search. There’s no formula for it.

Learning without gradients: keep the best, breed noisy copies

Most of the machine learning you read about trains networks with backpropagation: work out, for every weight, which way to nudge it to make the error smaller, and nudge. That needs a precise right answer for every example. Here there isn’t one. Nobody can say what the elevator should have been at second 14 of a take-off; you can only watch the whole flight and say how well it went.

So the learner is neuroevolution, the same method used earlier to teach a car to race round a track (that project is in Teaching a car to drive). It works like breeding, and it needs nothing but a score:

  1. Make 1,000 pilots with random weights.

  2. Let every one fly the same few situations, and give each a score.

  3. Keep the best, make mutated copies of the good ones, throw away the rest.

  4. Repeat.

Step 3, in full:

def next_generation(genomes, fitness, rng, keep=0.05, parents=0.20, mutation=0.1):
    n = len(genomes)
    ranked = np.argsort(-fitness)
    n_keep, n_parents = max(1, int(n * keep)), max(1, int(n * parents))
    survivors = genomes[ranked[:n_keep]]
    chosen = ranked[rng.integers(0, n_parents, size=n - n_keep)]
    children = genomes[chosen] + rng.normal(0.0, mutation, size=(n - n_keep, genomes.shape[1]))
    return np.vstack([survivors, children])

Three ideas live in those seven lines, and each has a name you’ll meet elsewhere:

There’s no crossover (mixing two parents) and no gradient anywhere. The number that decides who survives is the fitness: the pilot’s score. Everything the pilot was meant to do has to be expressed in that score, because it’s the only thing the learner ever hears. Writing that score took more of the project’s effort than anything else.

The simulator tells the pilot only what a pilot would know

BigSkySim has an HTTP API for flying a plane from a program: read the instruments, set the controls, step the clock a quarter of a second at a time. It gives a program what a pilot gets and nothing more. The readings are rounded the way a person reads a gauge: bank to 5°, pitch to 2.5°, vertical speed to 50 ft/min. And there are no coordinates. The view out of the window comes as word-pictures (“2 white 2 red” for the approach lights), and position as a radio-call phrase like “late downwind, 2.5 NM SE of the runway 27 threshold”. (More on the simulator in BigSkySim.)

The example Python client flying one circuit through the command API with --verbose on, at 4 times real time: every request and response on the left, the simulator on the right.

The first world to practise in was a model of the plane

Evolution needs a staggering amount of practice: a thousand pilots, a dozen situations each, a minute or so of flying each, for a hundred generations, comes to tens of thousands of hours. The first measurement said the simulator, answering through a browser over HTTP, ran at about real time, roughly 65 ms per request. At that speed one training run would take years.

So the first plan was a stand-in: a fast model of the aeroplane, learned from recordings of the real one, for the pilots to practise on. To learn how a plane responds to its controls, you have to see it respond to lots of different ones, so a small script took off and then deliberately wobbled: every 1 to 5 seconds it picked new random targets for pitch, bank and throttle, with guard rails that took over if the plane got too slow, too fast or too low. That gave about 15 minutes of deliberately untidy flying.

Supervised learning: when you do know the right answer

Building the stand-in is a different kind of learning from evolving pilots. Every tick of a recording is a worked example: here’s what the plane was doing and what the controls were, and here’s what really happened a quarter of a second later. When you have the right answer for every example, it’s called supervised learning, and it’s far more efficient than evolution, because the learner is told exactly how wrong it was every time.

Each example’s input is the last four ticks (one second) of readings and controls, flattened into one row of 45 numbers. The history is there because of the rounding: the pitch reading didn’t change at all on 63% of ticks. One reading can’t tell you which way the needle is moving; four usually can.

The model is linear: each predicted change is a weighted sum of the 45 inputs, one layer of the pilot’s network without the squashing. Fitting it is least squares, the line of best fit a spreadsheet draws through a scatter plot, done in 45 dimensions at once. It’s one line of linear algebra:

def fit(self, X, Y, ridge=1.0):
    self.mean = X.mean(axis=0)
    self.scale = X.std(axis=0)
    self.mean[-1], self.scale[-1] = 0.0, 1.0          # leave the constant 1 alone
    self.scale[self.scale == 0] = 1.0
    Xs = (X - self.mean) / self.scale
    n = Xs.shape[1]
    # The least-squares answer, in one line of linear algebra: W = (XᵀX + ridge·I)⁻¹ XᵀY
    self.W = np.linalg.solve(Xs.T @ Xs + ridge * np.eye(n), Xs.T @ Y)
    return self

That learned 405 weights from 4,989 examples in under two milliseconds. (ridge pulls every weight gently towards zero, so the fit doesn’t lean on inputs that only matter by coincidence.) Reading the weights back showed the model had worked out for itself that the best predictor of where the bank goes next is “bank now minus bank a moment ago”: how fast the needle is moving.

Test on what it never saw

The stand-in learned from three recorded flights and was tested on a fourth it never saw. That’s a held-out test set, the single most important habit in machine learning. Testing a model on the data it learned from is like marking your own homework with the answer sheet open: it only measures memory. What you want is generalisation, doing well on situations the model hasn’t met, and the only way to measure it is on data kept out of the learning.

The honest test let the stand-in fly on its own predictions, feeding each answer back in, given only the controls the real plane was given. Errors compound, as in any simulation that integrates its own output. After 30 seconds it was typically off by about 2 kt, 4° of bank and 33 ft; heading was the weak spot, at 19°. And it flew those 30 seconds in about a millisecond.

Six small charts of pitch, vertical speed, bank, altitude, airspeed and heading over 30 seconds, the real plane in black and the stand-in in red.
The same 30 seconds of control movements, flown by the real physics (black) and the stand-in model (red). Altitude drifts apart first.

A model only knows what its training data covered. Being linear, the stand-in had no idea that planes stall when they’re slow, and evolution would find that and breed pilots that only work in the stand-in. So a plane that left the range of the recordings (airspeed outside 68 to 105 kt, bank beyond 42°, and so on) counted as crashed. That fence comes back twice later on.

The first pilot flew the real plane at its first attempt

The first task was a cruise pilot: from wherever the plane is, get to 1,000 ft on the heading you’re given, and stay there. Its score, for every quarter-second:

def points(where, target_hdg):
    """Score for one tick, 0..1: full marks within a few feet and degrees of the target,
    falling to nothing at 200 ft or 30 degrees off."""
    alt_ok = np.clip(1 - np.abs(TARGET_ALT - where[:, 0]) / 200, 0, 1)
    hdg_ok = np.clip(1 - np.abs(wrap(target_hdg - where[:, 1])) / 30, 0, 1)
    return alt_ok * hdg_ok

The two parts are multiplied, so both have to be right at once. The targets come in as errors (“200 ft too low”) rather than raw readings, so the same brain works for any target. And the stand-in’s exact numbers were rounded to the real gauges’ resolution before the pilot saw them, so it couldn’t learn to rely on precision it would never get in the real plane: a small, deliberate case of making training look like production.

Before any learning, 98% of a thousand random brains left the fence and the median scored 0%. That’s normal. Evolution only needs a few to be slightly less bad than the rest.

Fresh practice every generation, a fresh exam at the end

Two choices in the training loop guard against overfitting, which is learning the practice questions rather than the subject:

    for gen in range(generations):
        starts, targets = pick_starts(flights, starts_per_gen, rng)
        fitness = trial(genomes, model, starts, targets, smooth=smooth)
        if gen < generations - 1:
            genomes = next_generation(genomes, fitness, rng)
    # The champion: the final generation's top 50, re-tested on 100 starts none of them have
    # flown. Picking on the training starts alone would favour whoever got lucky.
    top = genomes[np.argsort(-fitness)[:50]]
    starts, targets = pick_starts(flights, 100, rng)
    exam_scores = trial(top, model, starts, targets, smooth=smooth)
    return top[np.argmax(exam_scores)], np.array(history)

Every generation flies 12 new starting situations, so no brain can learn one by heart. And because the last generation’s top scorer may just have drawn easy starts, the top 50 sit a separate exam, and the best on it becomes the champion. Much later, that step turned out to have a bug in it.

The first loophole: banging the controls

Sixty generations on the stand-in took about a minute (at the real simulator’s speed, around 500 days). The champion did the job: every start ended at 1,000 ft on its heading. It also slammed the elevator and throttle from one end to the other, every quarter-second. The score said where to be and nothing about how, so frantic stick-work cost nothing. The fix was to add “smoothly” to the score:

def twitchiness(c, c_prev):
    """How much the stick and throttle moved this tick: average change, as a fraction of 50%."""
    return (np.abs(c - c_prev)[:, [0, 1, 3]] / 50).mean(axis=1)

Each tick’s points became points - 0.5 × twitchiness. On 200 new starts, scored on the task alone, the smooth champion did slightly better than the jerky one (68.9% against 67.4%), with controls moving about seven times less. So the jerkiness had never been helping; it had persisted only because nothing penalised it.

Then both champions flew the real BigSkySim, which neither had ever touched, from three awkward situations each, and all six flights ended near 1,000 ft on heading 270. But the smooth pilot had learned to descend as steeply as the fence allowed, up to 1,050 ft/min against a fence at 1,100. It flew right along the edge. The fence was a training rule that the aeroplane knows nothing about, and the learner pushed against it like any other rule.

Measure the slow thing before you replace it

Then a closer measurement changed the plan. Of those 65 milliseconds per request, almost all was the network and the browser relaying it. The physics took microseconds.

BigSkySim’s simulation core is plain JavaScript with no dependency on the browser, so it runs in Node too. A small batch mode now hosts many independent worlds in one Node process, one aircraft each, and Python runs one such process for nearly every CPU thread, sending one line of JSON per tick with the controls for all its planes. One generation of take-off practice, a thousand random brains each trying twelve random winds:

genomes = tp.random_genomes(1000, rng)
starts = tp.make_starts(12, rng)
fitness = tp.trial(genomes, pool, starts)
# 12,000 take-offs, 300 hours of flying, in 4.5 s

That’s about a quarter of a million times real time, on one desktop PC, on the simulator’s own physics with no approximation at all.

Overfitting to a simulator

With the real physics this fast, it was finally possible to ask what the stand-in had cost. The same brain, score and number of generations, trained on the real physics instead and held to the same limits on bank and pitch (the “normal flying” rule, below), scored about 5 points better on 191 unseen test situations, and was worse in none of them.

So part of the stand-in pilot’s skill had gone into flying the stand-in’s mistakes. That’s overfitting to a simulator, the machine learning version of a test suite that passes against a mock which behaves slightly differently from the real API. Only a comparison against the real thing could have shown that.

Running the core directly brought something else: it’s deterministic. The same seed and the same control inputs give exactly the same flight, every time. Rerunning the first 25 generations of the take-off training gives identical scores, generation by generation. It also means any moment of any flight can be rebuilt from a seed and a short script of control changes, which later becomes the fix for the hardest bug in the project.

The best-scoring pilot also flew the worst flight

Training on the real physics removed the fence, because a stall is now a real stall. The new champion beat the stand-in one by about 9 points on average. It also banked past 45° in more than half its flights, once past 110°, and in one went past vertical and dived at over 3,000 ft a minute. The score said where to be, and a steep bank gets you onto the heading a few seconds sooner.

The stand-in pilot had never done this only because the fence ended any trial past 42° of bank. A rule added to guard against the model’s ignorance had been teaching good manners without anyone meaning it to.

So the rule came back, on purpose this time, as part of what good flying means:

NORMAL = {'bank_deg': (-45, 45), 'pitch_deg': (-10, 15)}

Leaving that envelope ends the trial, like a crash. The normal-flying champion scored 82.9% against the stand-in pilot’s 77.5%, and banked past 45° once in 191 flights. The exam only caught the problem because it recorded the steepest bank of every flight as well as the score. Log the things you’d be embarrassed by as well as the number you’re optimising.

In reward terms, the limit is a hard constraint standing in for a reward term nobody wrote: passenger comfort. The pilot learned for itself how to turn within 45 degrees of bank, and the 45 itself is human judgement. Scoring comfort instead would have meant measuring what a passenger feels (bank, g-force, how quickly the plane rolls and pitches), deciding how much of each is acceptable, and letting the pilot find its own limits, perhaps better ones. That is more to specify and a harder search, so the constraint was the practical choice, and the same one instructors make when they tell a student to keep turns to 30 degrees of bank.

The take-off score is a history of loopholes

Next, the take-off: from standing still, full power, climb to 500 ft along the runway, in random winds up to 15 kt gusting up to 8 kt more. Left hands-off, the wind swings the nose round like a weathervane and the plane runs off the side of the runway within 12 seconds. The bar to beat was the hand-written take-off script from the recordings, which steered by heading: on 200 random winds it reached 500 ft in 152.

The take-off pilot’s score today, for every quarter-second:

def points(r, centreline=True, ball=True):
    c = lambda name: r[:, COL[name]]
    speed = np.clip(np.nan_to_num(c("airspeed_kt")) / 55, 0, 1)
    height = np.clip(np.nan_to_num(c("altitude_ft")) / TARGET_FT, 0, 1)
    hdg_ok = np.clip(1 - np.abs(wrap(RUNWAY_HDG - np.nan_to_num(c("heading_deg")))) / 30, 0, 1)
    p = hdg_ok * (0.3 * speed + 0.7 * height)
    if centreline:
        on_ground = c("on_ground") == 1
        line_ok = np.clip(1 - np.abs(np.nan_to_num(c("xtrack_m"))) / 15, 0, 1)
        p = np.where(on_ground, p * line_ok, p)
    if ball:
        in_air = c("on_ground") == 0
        ball_ok = np.clip(1 - np.abs(np.nan_to_num(c("slip_ball"))) / 3, 0, 1)
        p = np.where(in_air, p * ball_ok, p)
    return p

Every multiplication after the first line is a bug fix. Read it as a history.

Partial credit gives evolution somewhere to start

The first version was just the line that computes p: mostly for height, with full marks from 500 ft, a little for speed, all of it only while pointing along the runway.

Why the bit for speed? A random brain almost never leaves the ground. If the score only counted height, nearly all of the first generation would score zero, and selection would have nothing to choose between: a flat fitness landscape, with no “uphill” in any direction. The speed points say that accelerating down the runway is already better than running onto the grass. That’s partial credit, and it’s what lets evolution get going. In the first generation, 145 of 1,000 random brains got airborne for a moment and none reached 500 ft. That was enough. In about 20 generations they became pilots that take off, and the first champion reached 500 ft in 198 of 200 test winds.

Animation: eight pilots with random weights crash on the runway within seconds; the best pilot after 20 generations accelerates, lifts off and climbs to 500 feet.
Eight random pilots (grey, each crash marked with an orange ×) against the best pilot after 20 generations (blue), which takes off and climbs to 500 feet.

The champion ignored what the score didn’t mention

It also rolled down the runway a median of 8.6 m left of the centreline, because nothing in the score mentioned the centreline and that side was where the crosswind was easiest to hold. The centreline block multiplies the score on the ground by distance from the line, and a rule went in alongside it: more than 10 m off ends the trial. The next champion reached 500 ft in all 200 winds, a median of 2.2 m from the centreline.

Animation: one take-off, in one wind, seen from above with sideways distances stretched. The first champion swings about 7 metres off the centreline and stays there; the final champion stays within about a metre and a half of it.
One take-off, in one wind, from above with sideways distances stretched: the first champion against the final one.

That champion climbed with the rudder held hard over and the slip ball (which shows whether the plane is flying straight through the air or slightly sideways) well off centre, because nothing made flying sideways costly. The ball block fixed it, at a small cost elsewhere: with only 99 weights, every extra thing you ask for takes a little room from the others.

The other side of a literal optimiser is that it finds skills you never specified. Nobody told the take-off pilot about crosswinds; it just met a lot of them. In crosswinds of 10 to 15 kt, the hand-written script reached 500 ft 6% of the time, and the evolved pilot 100%.

Chart: take-offs completed in 200 random winds, by strength of crosswind. The hand-written script completes 94%, 56% and 6% as the crosswind rises; the learned pilot completes 100% in every band.
Take-offs completed in 200 random winds, by strength of crosswind: the hand-written script against the learned pilot.

A score needs both rules and points

By now the score had two kinds of thing in it, and they do different jobs:

LIMITS = dict(bank_deg=(-30, 30), pitch_deg=(-5, 15), stall_warning=(0, 0))
GROUND_LIMITS = dict(xtrack_m=(-10, 10))

Rules say what’s unacceptable, and end the trial. Points say what’s better. You need both: with only the 10 m rule, 9 m off scores exactly like dead centre, and with only points, a pilot can trade a few of them for a habit you never want to see.

The landing pilot learned to flare without being told

Practice landings start in the air: the local simulator puts the plane 1 to 2 km out on final, a little off the centreline and the 3° slope, at 60 to 72 kt, trimmed for the approach. Left hands-off in still air, dead on the slope, the plane lands itself at the aim point, but hits the runway still coming down at 350 ft/min, with no flare (the last-moment raise of the nose a pilot uses to touch down softly). The simulator only breaks the undercarriage at about 700 ft/min, so that counts as a landing: a loophole, waiting for the score. In random winds, hands-off, none of 200 approaches landed.

The landing pilot sees what a pilot sees, turned from the API’s words into numbers, including the PAPI, a row of four lights beside the runway: two white and two red means you’re on the slope, more white means high, more red means low. Its brain has 13 inputs, 10 hidden units and 5 outputs (adding throttle and brake): 195 weights, for a job with three phases (approach, flare and landing roll) in one brain.

PAPI approach lights A side view of the approach. Four lights stand beside the runway. An aircraft above the approach slope sees four white lights, one on the slope sees two white and two red, and one below it sees four red. runway PAPI the approach slope Too highfour white On the slopetwo white, two red Too lowfour red
The PAPI lights beside the runway tell the pilot whether the approach is too high, on the slope or too low. The slope is drawn steeper than the real 3 degrees so the three heights separate.

Most of what matters in a landing happens at one moment, so the score has parts: up to 30 for the approach, 50 for the touchdown and 20 for stopping. The touchdown points multiply being in the touchdown zone, on the centreline, and soft, which closes the hands-off loophole: full marks at 150 ft/min or less, nothing at 600. Nobody told the pilot how to touch down softly. It learned to flare anyway, easing a descent of about 300 ft/min to about 50 in the last few feet.

Chart: how fast the plane comes down by height above the runway. Hands-off it descends at a steady 350 feet per minute all the way down; the learned pilot eases off to about 50 feet per minute at touchdown.
The flare: descent rate by height above the runway, hands-off against the learned landing pilot.

Full power and full brakes, at the same time

The first landing champion (100 generations, about 14 minutes) landed 194 of 200 exam approaches, but stopped on the runway in only 129. After touchdown it put the brakes full on and the throttle wide open, at once. On the approach it had learned “speed dropping, add power”, exactly right in the air. On the runway the speed always drops, so the same reflex opened the throttle, and the score only asked whether the plane was stopped at the end.

Points for a short landing roll halved the median roll, from 517 m to 262 m. But the reflex was still there: a few seconds after touchdown the throttle opened fully, and the brakes won anyway. Removing the habit needed a rule: more than 20% throttle on the runway ends the landing.

The rule needed partial credit

The first version of that rule was all or nothing: break it and lose all the stop points. Trained from random brains, the pilot learned to land beautifully and never stopped once. A brain that waited ten seconds before opening the throttle scored exactly the same as one that opened it at once, so evolution had no “warmer, colder” to follow.

Two changes fixed it. A breach still ends the landing, but keeps partial credit for how much of its touchdown speed the plane had already shed:

def slowed(speed, td_speed):
    """How much of its touchdown speed a plane had lost, 0..1 (for the throttle rule)."""
    with np.errstate(invalid="ignore", divide="ignore"):
        return np.nan_to_num(np.clip(1 - np.abs(speed) / np.abs(td_speed), 0, 1))

And instead of starting from random brains, the run started from the existing champion:

if start_from is not None:
    genomes = start_from + rng.normal(0.0, 0.1, size=(population, np.size(start_from)))
    genomes[0] = start_from

That’s a warm start, or fine-tuning: the first generation is the existing pilot plus 999 mutated copies, so the only thing left to learn is one habit. The software equivalent is patching the current release rather than rewriting it. The slope gives the search a direction; the warm start puts it somewhere the slope exists.

landing pilotlandedstoppedlanding roll
hands-off0 / 2000 / 200-
first champion194 / 200129 / 200517 m
points for a short roll198 / 200193 / 200262 m
plus the no-power rule198 / 200197 / 200156 m

The final version never broke the rule in 200 exam landings, and stopped from 61 kt in 10 seconds.

This figure is interactive and needs JavaScript. The text around it describes what it shows.

The landing pilot in a 14-knot crosswind with gusts: side view against the 3° approach slope above, view from above below. Use the slider or press play.

Three learned pilots, and a few lines of hand-written glue

A whole flight needs all three pilots, each good at one job: the take-off pilot to 500 ft, the cruise pilot holding a height and heading it’s given, and the landing pilot from about a mile out. Between them sits a navigator: a few dozen hand-written lines that know the shape of a circuit (the rectangle every training flight flies round the airfield, described in Flying a circuit), hand the cruise pilot a heading and height for each leg, and switch pilots at the handovers. Learned components with hand-written mode logic around them is how most real autopilots are built too, and it keeps each network small enough to train in minutes.

The cruise pilot only ever learned to hold 1,000 ft. To get 600 ft on the base leg, the navigator shows it an altimeter reading 400 ft too high, and it “climbs back” to what it thinks is 1,000 ft. Every engineer has written a shim like that, to meet a new requirement without changing old code.

The first try, 200 whole flights in 200 random winds: 167 took off, flew the circuit, landed and stopped. Sixteen were lost turning onto downwind. At each corner the navigator asked for the new heading all at once, a 90° change in one step. The cruise pilot had trained on big turns, but from wobbly, varied states, rarely from steady flight with a sudden jump in its target. It banked past the 45° rule and the flight ended. A real autopilot moves its target heading (the “heading bug”) at 3° a second. Doing the same lost no flights in the circuit at all. A learned component’s inputs include the shape of the commands you send it.

Distribution shift at the handover

Now all 200 reached the landing pilot, and 31 were lost there, all but one by banking past 30°. Yet the landing pilot had passed its own exam 197 times in 200.

It had practised from 60 to 72 kt, trimmed for the approach, flaps down. The circuit handed it a plane doing about 97 kt, often descending at 700 to 1,000 ft/min, with the flaps only starting to come down. That’s distribution shift: a model used on situations unlike the ones it learned on, like a service load-tested on one traffic pattern that meets a different one in production. The landing pilot’s own exam couldn’t reveal it, because the exam came from the same generator as its training.

Chart: airspeed when the landing pilot takes over. What it practised on sits between 60 and 72 knots; what a real circuit hands it sits around 97 knots, with no overlap at all.
Airspeed when the landing pilot takes over: what it practised on, against what a real circuit hands it.

The fix used determinism. handover_start turns a flight’s seed plus every control change it made into a script, about 2,860 steps long, that rebuilds the handover moment with a largest difference, on any reading, of exactly zero. The project flew 400 fresh circuits, captured each handover as a training start, and fine-tuned the landing pilot (another warm start) on half real handovers and half its usual approaches, so it didn’t forget the old job. On the 200 test circuits, 194 now stopped on the runway, up from 169. On its old exam it improved too, stopping in 199 of 200 against 197. Practising on harder starts made it a better landing pilot all round.

This figure is interactive and needs JavaScript. The text around it describes what it shows.

Three whole flights from above: the calmest crosswind of 200, and the strongest from each side. The trail shows who is flying: take-off pilot, cruise pilot, landing pilot. Use the slider or press play.

Train on the information production will give you

There was still one cheat in all of this. The navigator decided where to turn from the plane’s exact position, to the metre, which the local simulator exposes for scoring and the real API never does. The real API gives a pilot’s view: the instruments, the window, and a coarse position report (distance to half a nautical mile, direction to 45°, clock position from the nose).

So the navigator learned to turn on the cues pilots are taught, all of which are in that report:

def report_turns(leg, r):
    leg = leg.copy()
    leg[(leg == UPWIND) & (r[:, COL["far_nm"]] >= 1.0)] = CROSSWIND
    leg[(leg == CROSSWIND) & (r[:, COL["thr_is_deg"]] == 225)] = DOWNWIND
    behind = np.isin(r[:, COL["thr_clock"]], (5, 6, 7))
    leg[(leg == DOWNWIND) & behind & (r[:, COL["thr_nm"]] >= BASE_NM)] = BASE
    leg[(leg == BASE) & (np.abs(r[:, COL["line_amount"]]) <= 2)] = FINAL   # NaN (not in view) compares False
    return leg

In words: turn crosswind when the far end of the runway is a mile behind; downwind when the report puts you south-west of the threshold; base when the threshold is 45° behind the left wing; final when the centreline, seen from base, moves from “well” to the side to “moderately”.

The BASE_NM condition is a scar. “Turn base when the threshold is 45° behind the wing” is the textbook rule, and on its own it stopped only 127 of 200 flights. These circuits come out narrower or wider with the wind, and a narrow one turned base early and left a final too short to settle on. Adding “and at least 2.5 NM out” took it to 195. A rule written for people quietly depends on everything else the person knows.

Between turns, the navigator estimates its position by dead reckoning: you started on the runway, and since then you’ve flown at this airspeed, on this heading, drifting with the wind the windsock shows. Each position report pulls the estimate back inside what it allows.

Then the held-out test again. The cues and the 2.5 NM were chosen by looking at those 200 flights, so judging them on the same 200 would flatter them. On 500 new circuits, the navigator flying by the report stopped on the runway 489 times, against 488 for the version that knew exactly where it was.

More test flights before you pick a winner

The last improvement went after a habit near the ground: in gusts the wings rocked, and about one landing in a hundred ended with a wingtip on the runway. Two ideas, each a fine-tune of the landing pilot: a new sense (roll rate, since until then the pilot only saw the bank as a snapshot rounded to 5°), and new points for keeping the wings level below 60 ft. And both together.

The first results were baffling. On 2,000 whole flights, the roll-rate version lost 64 in the landing against 12 before, and setting the new input’s weights to zero still left it losing 54. The problem was in the selection.

Remember the champion-picking step: the top 50 sit an exam, here on 100 approaches. At failure rates of a few percent, 100 tries can’t tell pilots apart. This is variance, the noise in any measurement made from a small sample, and a few lines of simulation show how bad it is:

rng = np.random.default_rng(0)
bad, good = rng.binomial(100, 0.03, 100_000), rng.binomial(100, 0.005, 100_000)
print(f"the 3% pilot looks as good or better {np.mean(bad <= good):.0%} of the time")
for n in (100, 1000):
    b, g = rng.binomial(n, 0.03, 100_000), rng.binomial(n, 0.005, 100_000)
    print(f"  on {n:4d} tries: {np.mean(b <= g):.1%}")

A pilot that crashes 3% of the time looks at least as good as one that crashes 0.5% of the time on 13% of 100-try exams. On 1,000 tries, essentially never. If you’ve ever chased a flaky test that fails three runs in a hundred, you know the feeling: one green run proves very little.

Chart: the chance that a pilot who crashes 3% of the time looks at least as good as one who crashes 0.5% of the time, by number of test flights. About 75% on 10 flights, 13% on 100, and under 1 in 100,000 on 1,000.
How often a pilot that crashes 3% of the time looks at least as good as one that crashes 0.5% of the time, by number of test flights.

Now add 50 candidates. Pick the best of many noisy measurements and you systematically pick whoever got luckiest, so the winner always looks better than it really is. That’s the winner’s curse, named after auction winners who tend to have overpaid. It was sitting in the project’s own pipeline, in the step written specifically to avoid being fooled.

Two changes fixed it: judge on 1,000 approaches, not 100, and keep the starting pilot in the candidate set, so that a fine-tune can never come back worse than it began:

top = genomes[np.argsort(-fitness)[:50]]
if start_from is not None:
    top = np.vstack([top, start_from])
exam_scores = trial(top, pool, held_out, **rules)
return top[np.argmax(exam_scores)], np.array(history)

There’s a second-order version of the same trap. Having compared six pilots on the same 2,000 circuits, picking the best of them on those circuits flatters the winner too. So the final comparison ran on 2,000 fresh circuits that played no part in any choice:

landing pilot (fresh circuits, used once)lost in the landingrocky landings (banked 15° or more below 60 ft)
before14 / 2,00049%
level-wing points, first round11 / 2,00032%
level-wing points, second round5 / 2,00024%
roll-rate sense and level-wing points8 / 2,00052%

The points halved the rocking. The new sense didn’t help, with or without them: at this amount of evolution, it found no use for it. An idea that sounds obviously right still needs the test.

Chart: landings where the wings rocked 15 degrees or more in the last 60 feet, out of 2,000 fresh circuits: 49% before, 24% after adding points for level wings.
Rocky landings, out of 2,000 fresh circuits, before and after adding points for level wings.

With the final three pilots and the report-flying navigator, 199 of 200 whole flights stopped on the runway, touching down a median of 140 m in, 0.8 m off the centreline, at 50 ft/min.

The final exam couldn’t be gamed

Everything so far ran on the simulator’s physics locally. The final exam was the real BigSkySim, in a browser, through its ordinary HTTP API: one plane at a time, the clock paused and stepped a quarter of a second at a time, with nothing in the code able to see where the plane really was.

Ten whole flights. Ten stopped on the runway, touching down 100 to 200 m past the threshold, within 2 m of the centreline, at 0 to 200 ft/min. The weak spot is still gusts: every pilot’s rare failures are a wingtip strike in strong gusts with little steady wind. And none of the pilots can go around: when an approach floats too long, a real pilot climbs away and tries again, and a few local test flights simply flew on.

Ten circuit tracks drawn from the navigator's own estimate of position, take-off in orange, circuit in blue, landing in purple.
The ten real-simulator flights as the navigator believed them: orange take-off, blue circuit, purple landing. The steps in the lines are the navigator correcting itself from a position report.

I’ve kept the lessons light here, because they deserve their own space. The short version is that the score is the specification, the learner reads it literally, and most of the real bugs were at the boundaries: between the model and reality, between one learned part and the next, and inside the project’s own way of choosing a winner. The longer version, and how it applies to building software and teams, is in The lessons and From the other end.

Ninety-nine numbers learned to fly a plane. Getting them to fly it the way it was meant took a precise score, a fast practice ground and honest tests.

Where next

Share this article

Email LinkedIn X

Comments

Loading comments...

Leave a Comment

All comments are moderated and may take a short while to appear.