neural6502
A neural network that is a MOS 6502, the processor in the Apple II and the BBC Micro, and, as the 6510, in the Commodore 64. It is trained to reproduce a reference emulator exactly, one bus cycle at a time, and then fed its own output to run real programs.
I picked the 6502 because the Commodore 64 was my first computer, and I learned machine code on it.
The one rule
All the CPU logic has to live in the network: decoding, addressing modes, arithmetic, flags, the stack. The code around it may only serve memory. If the network says write, store the byte. If it says read, hand back the byte at that address. It never decodes an instruction, adds an index register or computes a flag.
Where it stands
The goal was 100% on every opcode and every test case. It is reached. First
by three networks voting, then by a single network trained a little
further on the cases the others still got wrong, and finally by a single network that
also runs the complete Klaus Dormann functional test, all 30,646,177
instructions, without an error. That network, mlp_clear3, is
available to download, and the code is
on GitHub.
| Test | Result |
|---|---|
ProcessorTests, one instruction at a time, all 1,510,000 cases including decimal mode, single network mlp_clear3 (and the earlier mlp_single3) | all 1,510,000 exact, 0 wrong |
| Same tests, vote of three independently trained networks | all 1,510,000 exact, 0 wrong |
Best network trained from scratch only (mlp_indep4) | 1,509,979 exact, 21 wrong |
| Opcodes with every one of those cases right | 151 of 151, for the single network and for the vote |
| Seven real programs (sum, Fibonacci, multiply, bubble sort, sieve, memory copy, decimal arithmetic), checked after every instruction | all bit-exact |
Klaus Dormann's functional test, complete, mlp_clear3 | all 30,646,177 instructions, no error (decimal part included; 307 segments, each checked after every instruction) |
Same test, mlp_single3 (also 100% on ProcessorTests) | 305 of 307 segments right; the first wrong result is at instruction 11,819,741 |
| Same test, vote of three networks | 300,000 instructions, no error (the run limit) |
| Same test, best network trained from scratch only | 80,818 instructions, then a wrong result on SBC abs,Y |
| Each network | residual MLP, three blocks of 512, 1.69 million parameters |
| Networks trained | 17 (sixteen MLPs and one mixture-of-experts experiment); a vote uses three |
| Trained on | a 4-core laptop CPU (the GPU died early on) |
The complete test was run in pieces, because one process would need four to five days: how that works and what it turned up. The vote of three has not been run to the end; at 35 instructions per second that would take about nine days.
How it works
A CPU is a function: given its state and the byte that just arrived from memory, it produces the next state and a request to memory. One network evaluation is one clock cycle, with at most one memory access. Everything is bits: 100 in, 119 out, and every output bit is a separate yes or no. After each step the outputs are rounded to 0 or 1 and the 92 state bits go straight back in.
There is no dataset. Every training example is generated on the fly from a reference emulator that was itself checked against two standard test suites, with extra weight on the cases a network keeps getting wrong.
Single instructions
Every ProcessorTests case was run through the network on its own: it gets the starting memory, runs the instruction, and the registers and memory must match exactly afterwards. The first three networks were not trained on decimal mode, so their rows leave out its 80,093 cases; the later ones are scored on everything.
| Network | Exact | Failures | Opcodes all right |
|---|---|---|---|
mlp_long | 1,429,576 (99.977%) | 331 | 82 / 151 |
mlp_polish | 1,429,756 (99.989%) | 151 | 110 / 151 |
mlp_indep (new, from scratch) | 1,429,872 (99.998%) | 35 | 126 / 151 |
mlp_indep4, all cases incl. decimal | 1,509,979 (99.999%) | 21 | 136 / 151 |
mlp_clear3, one network, all cases | 1,510,000 (100%) | 0 | 151 / 151 |
mlp_single3, one network, all cases | 1,510,000 (100%) | 0 | 151 / 151 |
vote of mlp_indep2 + indep3 + indep4, all cases | 1,510,000 (100%) | 0 | 151 / 151 |
The worst early spots, the compares CPY and CPX, turned out to be
a data problem, not a network problem: with random memory a byte equals a register only
once in 256 tries, so the network had barely seen the most important case of a compare.
Adding training data aimed at such edge cases (long carries across a page boundary,
compare results near $80, sums that land exactly on 256) is what removed most
of the remaining mistakes.
Whole programs
Programs assembled with the project's own assembler run side by side on the reference and on the network. After every instruction all registers and all 64 KiB of memory are compared, and the first difference stops the run.
| Program | Instructions | mlp_long | mlp_polish | mlp_indep | Vote of three |
|---|---|---|---|---|---|
| sum 1..100 (16-bit) | 905 | pass | pass | pass | pass |
| first 25 Fibonacci numbers | 262 | pass | pass | pass | pass |
| 8×8 multiply, 8 pairs, via a subroutine | 569 | pass | pass | pass | pass |
| bubble sort, 24 bytes | 4,212 | pass | pass | pass | pass |
| sieve of Eratosthenes to 255 | 3,220 | pass | fails at instruction 779 | pass | pass |
| fill 512 bytes, copy 300 through a pointer | 5,370 | pass | pass | pass | pass |
A seventh program does decimal (BCD) arithmetic: the 6502 has a mode where an add works on two-digit decimal numbers. The networks that were not trained for it derail at the first decimal carry. The decimal-trained ones, and the vote, run it bit-exactly (972 instructions).
Klaus Dormann's test
This is a test program written to break 6502 emulators. It exercises every instruction with every flag combination and stops at the first wrong result. How far a network gets is partly luck: the better network on single instructions can fail it earlier, because one of its rarer mistakes happens to sit early in the program.
| Network | Instructions before the first error |
|---|---|
mlp_polish | 6,734 |
mlp_long | 40,634 |
mlp_indep | 48,774 |
mlp_indep3 | 55,460 |
mlp_indep4 | 80,818 |
mlp_single3, one network | 11,819,741 (SBC $0105,Y) |
vote of indep2 + indep3 + indep4 | none in 300,000 (run limit) |
mlp_clear3, one network | none: the complete test, 30,646,177 instructions |
Why three networks
For a long time every single network still made an occasional mistake, and on a long program one mistake is enough to derail everything. So three networks run side by side and a bitwise majority vote decides each output bit. The vote does not decode or compute anything, so all the CPU logic still lives in the networks. Over the 1,083,260 steps of the first 300,000 Klaus instructions, one of the three had to be outvoted only 5 times; each of those would have been a mistake in a single network.
It only works if the networks make different mistakes. The first ensemble used three versions of the same network, each trained on from the last, and they shared a blind spot: on compares two of them outvoted the one that was right. The fix was networks with no shared history: trained from scratch, with another random seed and another activation function, and with extra data aimed at what the previous ones got wrong.
| ProcessorTests failures (binary-scored) | |
|---|---|
mlp_indep | 35 |
mlp_indep2 | 46 |
mlp_indep3 | 22 |
| vote of the three | 0 |
The last gap was decimal mode: two cases where the zero flag has to come from the binary
sum of $20 + $E0 while the accumulator gets the decimal result. A fourth
network trained on exactly such sums gets them right, and the vote of the three newest
networks, all trained with decimal mode, gets every one of the 1,510,000 cases right.
Back to one network
A vote is three times the work per cycle, and the question remained whether one network
can do it alone. mlp_indep4 was already almost perfect: its 21 remaining
failures were not things it could not learn, but inputs it had hardly ever seen, about one
instruction in 60,000.
So the voters became a searchlight. A search program generated millions of instructions with the project's own random generator, started each one exactly like the real test harness, and kept every step where the network was wrong, close to wrong (an output bit at 0.45 instead of near 0 or 1), or where one of the other networks was wrong. The right answers always come from the reference emulator. The network was trained a little further with these hard examples mixed into every batch, and the search ran again.
| Round | Searched | Real mistakes found | Close calls kept | Result | ProcessorTests failures |
|---|---|---|---|---|---|
| 1 | 3 million instructions, mlp_indep4 | 48 | 107,352 | mlp_single | 21 → 11 |
| 2 | 3 million, mlp_single | 19 | 23,743 | mlp_single2 | 11 → 1 |
| 3 | 4 million, mlp_single2 | 1 | 5,016 | mlp_single3 | 1 → 0 |
mlp_single3 is the same size as every other network, 1.69 million parameters,
and it runs the first 300,000 instructions of Klaus's test without a vote to fall back on,
three times as fast as the trio. The complete test turned out to be harder, as the next
section tells.
One honest caveat. The search never looked at ProcessorTests, but each round's network was scored on it once, to decide whether another round was needed. So the test suite decided when we stopped, not what the network was trained on. The one failure left after round 2 was not turned into training data; the search of round 3 found a mistake of exactly that kind by itself.
A complete run of the Klaus test
The complete test, with its decimal-mode part, is 30,646,177 instructions. At about 80 instructions per second one process would need four to five days, so the run is cut into 307 segments of 100,000 instructions. The reference emulator runs the test once and saves its whole state at every boundary: registers, internal state, all 64 KB of memory. Each segment starts the network from one of those states, runs it on its own output, compares everything after every instruction, and must end exactly on the next saved state. Because every segment starts where the reference was, 307 passing segments are the same as one uninterrupted run.
| Network | Segments right | What went wrong | Time |
|---|---|---|---|
mlp_single3 | 305 of 307 | instruction 11,819,741: SBC $0105,Y, accumulator $00 instead of $40; instruction 27,071,345: decimal SBC #$07, wrong zero flag | 5.4 days of CPU time |
mlp_clear3 | 307 of 307 | nothing | 18.5 hours, six processes |
So mlp_single3, perfect on all 1.51 million test cases, still made two mistakes
in the long test. Two things were behind them.
Leftovers from the previous instruction
Inside the network a few internal registers (the instruction register, two address bytes and a temporary) carry over from one instruction to the next. Every test case starts with them at zero, and so did the training; a running program does not. One of the failures only happened with a particular leftover value, and was right with zero. Training on random leftovers fixed that one case but not the weakness, so the protocol was changed instead: on the last step of an instruction the network now zeroes those registers itself. They are internal, so no program can tell the difference (a test checks that on every program and on Klaus), and the memory-only rule for the surroundings is untouched.
Narrow pockets
The other mistakes sat at one register value and one operand in one context, about one in 100,000 operand pairs. ProcessorTests tries 10,000 random cases per opcode and random mining almost never lands on such a pocket, but Klaus's loops try every operand pair. So the mining gained a sweep that does the same on purpose: for each of the 56 arithmetic and compare opcodes, random contexts times all 256 register values, all 256 operands and the carry and decimal flags, 262,144 rows each, labelled by the reference. A local search around close calls was added too. It varies only the start of an instruction and lets the reference run the whole instruction again, because changing the middle of one creates states no program can reach (the first attempt did, and produced tens of thousands of bogus failures that were thrown away).
| Round | Mined network | Network after | ProcessorTests failures |
|---|---|---|---|
| 4 | mlp_single3 | mlp_single4 | 0 → 0 |
| 5 | mlp_single4 | mlp_clear (zeroes the leftovers) | 0 → 3 |
| 6 | mlp_clear | mlp_clear2 | 3 → 1 |
| 7 | mlp_clear2 | mlp_clear3 | 1 → 0 |
The same caveat, and one more. No row of ProcessorTests or Klaus was ever
trained on; every label comes from the reference emulator. But Klaus was used to
diagnose: the two failing segments were inspected, which is how the leftovers and
the pockets were found, and each candidate network was tried on those two segments before a
full run. ProcessorTests was scored once per round, to decide whether to go on. What counts
is the complete run of mlp_clear3, in which those two segments are two of 307.
A screen, and a file you can take anywhere
The network also drives a text screen at $0400: a small program prints a title
and a table of Fibonacci numbers, adding in decimal mode, and the screen contents are
byte-for-byte identical to the reference. And one
network is exported as a single 6.8 MB ONNX file that runs all the programs bit-exactly
outside the training software.
What did not work
- Many small experts lost badly. A mixture of eight experts, one per instruction family, reached 75.6% of cycles exactly right and no perfect opcode. One network reached 99.93% and 97. Most of a 6502 is shared (addresses, the program counter, the stack, the N and Z flags), and splitting by instruction family cuts through exactly what has to be learned.
- A constant learning rate never converges. The count of perfect opcodes jumped around from run to run and only settled once the rate was lowered gradually.
- "99.9% on my own test set" meant little. The outside suites found every important bug; the network's own held-out set found none.
- "Almost wrong" is the signal. The last mistakes were too rare to find one by one. The inputs where a network was right but unsure were a thousand times more common, sat in the same places, and were enough to train the last mistakes away.
- Networks that grew up together make the same mistakes. Voting among relatives fixed the sieve but not Klaus. Voting among strangers fixed both.
Not planned: the 6510
The Commodore 64's 6510 runs the same instructions as the 6502, so the network can already run 6510 code. What the 6510 adds is a small input/output port at addresses 0 and 1 that switches memory between RAM, ROM and I/O chips. That is about how memory is wired rather than what the CPU computes, and this project keeps the memory around the network as plain as possible on purpose. So the 6510 itself is not on the plan.
Download
The code is on GitHub, under the MIT licence. The software,
the weights and the result files are also here as downloads. Unzip the software
and the weights into the same folder: the weights are laid out as
runs/NAME/final.pt, so the commands in the README work as they are. You need
Python with PyTorch, NumPy and PyYAML (ONNX and onnxruntime for the portable file).
| File | What is in it | Size | SHA-256 |
|---|---|---|---|
| The software neural6502-software.zip | Reference emulator, micro-step oracle, training code, mining tool, assembler, evaluation scripts, the 7 test programs, all training configs, the result files and the write-up's data, README and design notes. No test data (see below). | 0.6 MB | 2be12b7c6a0d30d0acdc1b1f50a6c5a3c29cda725ea8bda900f20dcd4d5b02a3 |
| All the weights neural6502-weights.zip | The final weights of all 16 networks (plain PyTorch state dicts, laid out as runs/NAME/final.pt so the commands in the README work) and three ONNX files. Unzip next to the software. | 124.7 MB | e553d91a34bff75fbc2883e7f067bf57d0974fb95d11923100f506099c760468 |
| The final network, PyTorch mlp_clear3.pt | mlp_clear3: one network that gets all 1,510,000 ProcessorTests cases right and runs the complete Klaus test, 30,646,177 instructions, without an error. 1.69 million parameters. | 6.8 MB | 480a12f3f925f9119c3d78ab8665c37bb72cf3dfefcc9fe869d21ab4c4176c04 |
| The final network, ONNX mlp_clear3.onnx | The same network as one portable file, checked bit-exact against the PyTorch version. The complete Klaus run was done on this file. Runs with onnxruntime. | 6.8 MB | e05706539722b7d6bed624bd09c60e29137bebcbad441fe02a50c038861e12b0 |
- The test suites (ProcessorTests and Klaus Dormann's functional test) are not included;
python -m neural6502.ref.downloadfetches them from their authors. - The training data is not a file either: it is generated on the fly. The mined hard-example sets from the last three rounds are not included.
- The weights are plain PyTorch state dictionaries, and the ONNX file is
mlp_clear3, the network that passes the complete Klaus run, with the same weights. - MIT licence, copyright Marcel Meijer and Kynto Software; provided as is, without warranty. The test suites keep their own licences.