← Research

Complete Klaus run passedOpen source, MIT

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.

Code on GitHub Downloads

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.

TestResult
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 networksall 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 right151 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 instructionall bit-exact
Klaus Dormann's functional test, complete, mlp_clear3all 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 networks300,000 instructions, no error (the run limit)
Same test, best network trained from scratch only80,818 instructions, then a wrong result on SBC abs,Y
Each networkresidual MLP, three blocks of 512, 1.69 million parameters
Networks trained17 (sixteen MLPs and one mixture-of-experts experiment); a vote uses three
Trained ona 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.

Opcodes that are 100% right during training, per run Line chart. The count of the 151 opcodes that are fully right on held-out examples, against training steps. It stays near zero for the first 8,000 steps, then climbs in jumps to 97 at 10,000 steps, wobbles between 2 and 98 while the learning rate is constant, and settles at 147 after the final polish run. A second run, the mixture of experts, stays at zero. 0 50 100 151 0k 10k 20k 30k 40k 50k training steps (cumulative) opcodes fully right (of 151) mlp_base mlp_long mlp_polish one network, trained in three stages mixture of experts (10k steps, stays at 0) 147
How many of the 151 opcodes the network gets completely right on held-out examples while it trains. This is a different measure from the ProcessorTests numbers elsewhere on this page, which count test cases from an outside suite. The count jumps around while the learning rate is constant and only settles once it is lowered.

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.

NetworkExactFailuresOpcodes all right
mlp_long1,429,576 (99.977%)33182 / 151
mlp_polish1,429,756 (99.989%)151110 / 151
mlp_indep (new, from scratch)1,429,872 (99.998%)35126 / 151
mlp_indep4, all cases incl. decimal1,509,979 (99.999%)21136 / 151
mlp_clear3, one network, all cases1,510,000 (100%)0151 / 151
mlp_single3, one network, all cases1,510,000 (100%)0151 / 151
vote of mlp_indep2 + indep3 + indep4, all cases1,510,000 (100%)0151 / 151
Every official opcode, and how many ProcessorTests cases it fails A 16 by 16 grid of opcodes. 136 of the 151 official opcodes are right on every test case; the others show how many of their cases fail, 21 in total. Compares such as CPY and CPX fail most. x0 0x x1 1x x2 2x x3 3x x4 4x x5 5x x6 6x x7 7x x8 8x x9 9x xA Ax xB Bx xC Cx xD Dx xE Ex xF Fx $00 BRK imp: all 10000 cases right $01 ORA izx: all 10000 cases right $05 ORA zp: all 10000 cases right $06 ASL zp: all 10000 cases right $08 PHP imp: all 10000 cases right $09 ORA imm: all 10000 cases right $0A ASL acc: all 10000 cases right $0D ORA abs: all 10000 cases right $0E ASL abs: all 10000 cases right $10 BPL rel: all 10000 cases right $11 ORA izy: all 10000 cases right $15 ORA zpx: all 10000 cases right $16 ASL zpx: all 10000 cases right $18 CLC imp: all 10000 cases right $19 ORA aby: all 10000 cases right $1D ORA abx: all 10000 cases right $1E ASL abx: all 10000 cases right $20 JSR abs: all 10000 cases right $21 AND izx: all 10000 cases right $24 BIT zp: 1 of 10000 cases fail 1 $25 AND zp: all 10000 cases right $26 ROL zp: all 10000 cases right $28 PLP imp: all 10000 cases right $29 AND imm: all 10000 cases right $2A ROL acc: all 10000 cases right $2C BIT abs: all 10000 cases right $2D AND abs: all 10000 cases right $2E ROL abs: all 10000 cases right $30 BMI rel: all 10000 cases right $31 AND izy: all 10000 cases right $35 AND zpx: all 10000 cases right $36 ROL zpx: all 10000 cases right $38 SEC imp: all 10000 cases right $39 AND aby: all 10000 cases right $3D AND abx: all 10000 cases right $3E ROL abx: all 10000 cases right $40 RTI imp: all 10000 cases right $41 EOR izx: all 10000 cases right $45 EOR zp: all 10000 cases right $46 LSR zp: all 10000 cases right $48 PHA imp: all 10000 cases right $49 EOR imm: all 10000 cases right $4A LSR acc: all 10000 cases right $4C JMP abs: all 10000 cases right $4D EOR abs: all 10000 cases right $4E LSR abs: all 10000 cases right $50 BVC rel: all 10000 cases right $51 EOR izy: all 10000 cases right $55 EOR zpx: all 10000 cases right $56 LSR zpx: all 10000 cases right $58 CLI imp: all 10000 cases right $59 EOR aby: all 10000 cases right $5D EOR abx: all 10000 cases right $5E LSR abx: all 10000 cases right $60 RTS imp: all 10000 cases right $61 ADC izx: all 10000 cases right $65 ADC zp: all 10000 cases right $66 ROR zp: all 10000 cases right $68 PLA imp: all 10000 cases right $69 ADC imm: all 10000 cases right $6A ROR acc: all 10000 cases right $6C JMP ind: all 10000 cases right $6D ADC abs: all 10000 cases right $6E ROR abs: all 10000 cases right $70 BVS rel: all 10000 cases right $71 ADC izy: 1 of 10000 cases fail 1 $75 ADC zpx: all 10000 cases right $76 ROR zpx: all 10000 cases right $78 SEI imp: all 10000 cases right $79 ADC aby: all 10000 cases right $7D ADC abx: all 10000 cases right $7E ROR abx: all 10000 cases right $81 STA izx: 1 of 10000 cases fail 1 $84 STY zp: all 10000 cases right $85 STA zp: all 10000 cases right $86 STX zp: all 10000 cases right $88 DEY imp: all 10000 cases right $8A TXA imp: all 10000 cases right $8C STY abs: all 10000 cases right $8D STA abs: all 10000 cases right $8E STX abs: all 10000 cases right $90 BCC rel: all 10000 cases right $91 STA izy: 1 of 10000 cases fail 1 $94 STY zpx: all 10000 cases right $95 STA zpx: all 10000 cases right $96 STX zpy: all 10000 cases right $98 TYA imp: all 10000 cases right $99 STA aby: all 10000 cases right $9A TXS imp: all 10000 cases right $9D STA abx: all 10000 cases right $A0 LDY imm: all 10000 cases right $A1 LDA izx: all 10000 cases right $A2 LDX imm: all 10000 cases right $A4 LDY zp: all 10000 cases right $A5 LDA zp: all 10000 cases right $A6 LDX zp: all 10000 cases right $A8 TAY imp: all 10000 cases right $A9 LDA imm: all 10000 cases right $AA TAX imp: all 10000 cases right $AC LDY abs: all 10000 cases right $AD LDA abs: all 10000 cases right $AE LDX abs: all 10000 cases right $B0 BCS rel: all 10000 cases right $B1 LDA izy: all 10000 cases right $B4 LDY zpx: 1 of 10000 cases fail 1 $B5 LDA zpx: all 10000 cases right $B6 LDX zpy: all 10000 cases right $B8 CLV imp: all 10000 cases right $B9 LDA aby: all 10000 cases right $BA TSX imp: all 10000 cases right $BC LDY abx: all 10000 cases right $BD LDA abx: 1 of 10000 cases fail 1 $BE LDX aby: 1 of 10000 cases fail 1 $C0 CPY imm: all 10000 cases right $C1 CMP izx: all 10000 cases right $C4 CPY zp: 1 of 10000 cases fail 1 $C5 CMP zp: all 10000 cases right $C6 DEC zp: all 10000 cases right $C8 INY imp: all 10000 cases right $C9 CMP imm: all 10000 cases right $CA DEX imp: all 10000 cases right $CC CPY abs: 2 of 10000 cases fail 2 $CD CMP abs: all 10000 cases right $CE DEC abs: all 10000 cases right $D0 BNE rel: all 10000 cases right $D1 CMP izy: all 10000 cases right $D5 CMP zpx: all 10000 cases right $D6 DEC zpx: all 10000 cases right $D8 CLD imp: all 10000 cases right $D9 CMP aby: all 10000 cases right $DD CMP abx: 1 of 10000 cases fail 1 $DE DEC abx: all 10000 cases right $E0 CPX imm: 1 of 10000 cases fail 1 $E1 SBC izx: all 10000 cases right $E4 CPX zp: 1 of 10000 cases fail 1 $E5 SBC zp: all 10000 cases right $E6 INC zp: all 10000 cases right $E8 INX imp: all 10000 cases right $E9 SBC imm: 1 of 10000 cases fail 1 $EA NOP imp: all 10000 cases right $EC CPX abs: all 10000 cases right $ED SBC abs: all 10000 cases right $EE INC abs: all 10000 cases right $F0 BEQ rel: 5 of 10000 cases fail 5 $F1 SBC izy: 2 of 10000 cases fail 2 $F5 SBC zpx: all 10000 cases right $F6 INC zpx: all 10000 cases right $F8 SED imp: all 10000 cases right $F9 SBC aby: all 10000 cases right $FD SBC abx: all 10000 cases right $FE INC abx: all 10000 cases right
Every official opcode, for the best network trained from scratch (the 100% network, mlp_single3, would be all green). A number is how many of that opcode's ProcessorTests cases it gets wrong; a plain green cell fails none; a hollow cell is not an official opcode. Hover a cell for its name.

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.

ProgramInstructionsmlp_longmlp_polishmlp_indepVote of three
sum 1..100 (16-bit)905passpasspasspass
first 25 Fibonacci numbers262passpasspasspass
8×8 multiply, 8 pairs, via a subroutine569passpasspasspass
bubble sort, 24 bytes4,212passpasspasspass
sieve of Eratosthenes to 2553,220passfails at instruction 779passpass
fill 512 bytes, copy 300 through a pointer5,370passpasspasspass

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.

NetworkInstructions before the first error
mlp_polish6,734
mlp_long40,634
mlp_indep48,774
mlp_indep355,460
mlp_indep480,818
mlp_single3, one network11,819,741 (SBC $0105,Y)
vote of indep2 + indep3 + indep4none in 300,000 (run limit)
mlp_clear3, one networknone: 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_indep35
mlp_indep246
mlp_indep322
vote of the three0

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.

RoundSearchedReal mistakes foundClose calls keptResultProcessorTests failures
13 million instructions, mlp_indep448107,352mlp_single21 → 11
23 million, mlp_single1923,743mlp_single211 → 1
34 million, mlp_single215,016mlp_single31 → 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.

NetworkSegments rightWhat went wrongTime
mlp_single3305 of 307instruction 11,819,741: SBC $0105,Y, accumulator $00 instead of $40; instruction 27,071,345: decimal SBC #$07, wrong zero flag5.4 days of CPU time
mlp_clear3307 of 307nothing18.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).

RoundMined networkNetwork afterProcessorTests failures
4mlp_single3mlp_single40 → 0
5mlp_single4mlp_clear (zeroes the leftovers)0 → 3
6mlp_clearmlp_clear23 → 1
7mlp_clear2mlp_clear31 → 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

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).

FileWhat is in itSizeSHA-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 MB2be12b7c6a0d30d0acdc1b1f50a6c5a3c29cda725ea8bda900f20dcd4d5b02a3
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 MBe553d91a34bff75fbc2883e7f067bf57d0974fb95d11923100f506099c760468
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 MB480a12f3f925f9119c3d78ab8665c37bb72cf3dfefcc9fe869d21ab4c4176c04
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 MBe05706539722b7d6bed624bd09c60e29137bebcbad441fe02a50c038861e12b0
Read the full write-up All research