I Built a Custom AI GPU on a $25 FPGA.
Here is What it Taught Me About Computer Architecture.
From software abstractions to physical wires, clock ticks, latency hiding, and writing a compiler from scratch.
If you write software today, you probably use AI. You load up PyTorch or TensorFlow, type a few lines of Python, and magic happens. But I wanted to know what happens underneath the Python. What is physically happening to the electricity inside the silicon? Why do we need GPUs instead of CPUs to run these models?
To find out, I decided to build one.
I designed a custom 16-bit SIMT (Single Instruction, Multiple Threads) GPU from scratch, flashed it onto a $25 Tang Nano 20K FPGA, and even wrote my own programming language (J++) and compiler in Rust to write kernels for it.
This project completely broke my software-engineer brain and rebuilt it. By tracing the math down to the microscopic logic gates, I learned how computers actually work. Here is a top-down deconstruction of modern computer architecture, explained through the physical hardware I had to build.
The GPU: A High-Level Schematic
Before diving into the components, here is a bird's-eye view of the entire system architecture. Notice how the host PC is entirely detached from the execution, only feeding instructions and data via UART, while the FPGA handles all dispatching and SIMT execution.
Host Environment (Laptop)
Tang Nano 20K FPGA (The GPU)
Compute Core 0Active
Compute Core 1
Core Instance)
Part 1: The System Hierarchy
A GPU isn't just a single block of math. It is a strictly organized hierarchy designed to keep the math workers fed with data at all times. My design has three layers: a Host that loads work, a Dispatcher that divides it, and the Cores that execute it.
The Host-Driven Harness (No CPU Allowed)
My FPGA board has no CPU. It relies entirely on my laptop (the Host) to tell it what to do. I built a DMA (Direct Memory Access) Engine wired to the board's USB UART receiver. My laptop sends a binary payload over USB, and the DMA hardware catches those bytes and streams them directly into the FPGA's internal memory. Once the payload is fully loaded, the DMA pulses a physical gpu_start wire to wake up the silicon.
The Dispatcher & Independent Cores
Once awake, the gpu_start signal hits the Dispatcher. The Dispatcher's job is incredibly simple: it looks at the available work, hands Block 0 to Core 0, hands Block 1 to Core 1, and waits for them to finish.
I gave each Core its own independent Program Counter (PC) and its own copy of the program memory. Why? Because if they shared one memory port, they would fight over it. By physically duplicating the memory, Core 0 and Core 1 run genuinely in parallel, completely independent of each other.
Part 2: Inside the Compute Core & All Physical Components
Zooming into a single Core, we move from management to raw execution. A Core is a single Warp Scheduler driving shared execution resources.
The Complete Component Breakdown
To make this work, the GPU requires several specialized hardware blocks working in unison. Here is every major physical component I had to design in Verilog:
- DMA Engine (Direct Memory Access): Listens to the USB UART, collects the binary program and data payloads, and writes them directly into the SRAM before execution starts.
- Global Dispatcher: The manager that wakes up when the DMA is done. It assigns thread blocks to available Cores.
- SRAM (Shared Memory): 8 KB of block RAM on the FPGA that holds both the compiled instructions and the data (like neural network weights).
- Program Counter (PC): A dedicated register that points to the current address of the instruction being executed.
- Instruction Fetch Unit: Reads the 16-bit instruction from SRAM at the address the PC points to.
- Hardware Decoder: The "switchboard." It looks at the 16-bit instruction, decodes the opcode, and flips the physical wires to activate the correct math circuits.
- Register File: Extremely fast, local memory built directly out of flip-flops. Each ALU lane gets its own private bank of 8 physical registers (R0-R7).
- ALUs (Arithmetic Logic Units): The actual calculators. I built 4 ALUs per Core, meaning 4 threads execute math simultaneously. They can ADD, SUB, MUL, SHIFT, and compare numbers.
- Execution Mask & Reconvergence Stack: Hardware that tracks which threads are currently active during
if/elsestatements, allowing ghost threads to sleep and wake up when paths merge. - LSU Arbiter (Load/Store Unit): A traffic cop that takes 4 simultaneous memory requests from the ALUs, serializes them across 4 clock cycles to access the single-port SRAM, and funnels the data back to the correct threads.
- Warp Scheduler: The brain of the pipeline that rapidly swaps out active thread warps when one stalls on a memory fetch.
The 9-Stage Pipeline
In software, sum = a + b + c happens instantly. In hardware, time is dictated by physics.
My FPGA has a physical quartz crystal that vibrates at 27 MHz. An on-chip PLL multiplies that up: the design ships at 54 MHz (27 × 2), and I've validated it running as fast as 81 MHz (27 × 3) before timing breaks down. Electricity has to physically travel through microscopic logic gates to do math. If you string too many operations together using only copper wires, the electricity won't reach the end of the maze before the clock ticks. The chip will sample halfway-computed garbage and crash (a timing violation).
To solve this, I built a 9-Stage Pipeline using reg walls (hardware flip-flops that only open when the clock ticks). The pipeline walks through 9 physical states:
IDLE → SELECT_WARP → FETCH → DECODE → REQUEST → WAIT → EXECUTE → UPDATE → DONEThe Decoder and Per-Lane ALUs (True SIMT)
In the DECODE stage, a hardware Decoder takes a 16-bit binary instruction (like 0001001010000000) and acts like a massive switchboard operator. It violently routes electricity down different paths based on those 1s and 0s—turning on the "ADD" circuitry and opening the door to Register 1.
But here is what makes it a GPU: The Decoder doesn't send that signal to one ALU (Arithmetic Logic Unit). It yells it over a loudspeaker to multiple Per-Lane ALUs simultaneously. How do they do different work if they hear the same command? Thread IDs. I hardwired a unique ID (0, 1, 2...) into each ALU lane. When the Decoder yells "Load Pixel [Base + Thread_ID]", Lane 0 grabs Pixel A, Lane 1 grabs Pixel B. Massive parallelism achieved with a single instruction!
Part 3: The Hardware "Tricks" That Make it a GPU
A GPU isn't just parallel ALUs. It relies on a series of incredible hardware illusions to keep performance high.
Trick A: Multi-Warp Scheduling (Latency Hiding)
Memory is agonizingly slow. If an ALU needs a pixel from BRAM, it might have to wait 3 clock cycles. If the ALUs sit idle doing nothing for 3 cycles, you lose massive amounts of performance.
To fix this, I implemented Multi-Warp Scheduling in the SELECT_WARP pipeline stage. A "Warp" is a group of threads. I gave my GPU multiple warps. When Warp 0 executes an LDR (Load) instruction, the hardware puts Warp 0 into a WARP_WAITING state. But instead of the ALUs going to sleep, the Scheduler instantly looks at Warp 1 and says, "Your turn."
Warp 1 uses the ALUs to do math while Warp 0 is waiting for its memory to arrive. This is called Latency Hiding, and it is the secret sauce to keeping NVIDIA Tensor Cores fed at 100% utilization.
Trick B: Branch Divergence (The Ghost Threads)
If all threads share one brain, what happens when you write an if/else statement?
If I write if (x > 0), and Lane 0 passes but Lane 1 fails, they can't take different paths. They are physically locked together. To fix this, I built an Active Mask and a Reconvergence Stack.
When the warp hits a diverging branch, the hardware computes a bitmask (e.g., [1, 0]). The hardware pushes a "bookmark" containing the original mask and the end-address of the if block onto a physical memory stack.
Both threads physically execute the instructions inside the if block. However, the hardware turns off the "Write Enable" wire for the thread that failed (the 0). That thread becomes a "ghost." It does the math, but it leaves no trace in memory. When the PC reaches the bookmark address, the hardware pops the stack, restores the mask, and the ghosts come back to life to resume lockstep execution.
Trick C: The LSU Arbiter (The Traffic Cop)
My GPU has 8 KB of shared BRAM. Because it is a SIMT machine, a single LDR (Load) instruction means multiple threads request memory at the exact same nanosecond. But the BRAM only has one physical read port.
If they all shove their electrical signals into the port at once, the data is corrupted. I had to build an LSU Arbiter. This piece of hardware acts as a traffic cop. When a multi-thread load occurs, the Arbiter freezes the Warp pipeline, serializes the requests, and funnels them one-by-one through the single BRAM port across consecutive clock cycles. Once all the data is safely retrieved into the threads' local registers, the Arbiter wakes the Warp back up.
Part 4: The GPU ISA & Inventing the J++ Compiler
You can't just drop a Python script onto raw silicon. The hardware only understands raw electrical highs and lows (1s and 0s).
Defining the GPU ISA (Instruction Set Architecture)
I had to define a strict contract between the hardware and the software. Every command in the GPU is exactly 16 bits wide. I partitioned these bits into specific fields. For example, a math operation looks like this:
[Opcode: 4 bits] | [Dest Reg: 3 bits] | [Src1 Reg: 3 bits] | [Src2/Imm: 6 bits]If the hardware sees 0001 000 001 000010, the Decoder parses it as: ADD R0, R1, R2 (where Opcode 1 is ADD). Because it's a SIMT architecture, every ALU executes this instruction simultaneously, pulling from their own private banks of physical registers (R0-R7).
Writing the J++ Compiler in Rust
Writing 16-bit binary arrays by hand to compute gradients is a nightmare. So, I built a compiler from scratch in Rust for a custom, statically typed, C-like language I call J++. Building the compiler taught me how modern LLVM frontends bridge the gap to physical silicon.
- The Lexer & Parser: The frontend reads my
.jpptext and builds an Abstract Syntax Tree (AST). It maps mathematical expressions into nested nodes, fully aware of operator precedence. - Register Allocation (The Nightmare): The GPU only has 8 physical registers per thread. When an expression requires more than 8 variables at once, the compiler performs register spilling—automatically injecting
STR(Store) instructions to dump local variables to the BRAM, andLDR(Load) instructions to pull them back when needed. - Control Flow Lowering (Handling Branch Divergence): As mentioned in Trick B, an
if/elsestatement requires ghost threads. My compiler lowers a J++ifblock into custom hardware mask instructions:- It emits a
CMPinstruction to set the ALUs' condition flags. - It emits a
MASK_PUSHinstruction to save the current execution state to the hardware stack. - It turns off the threads that failed the condition based on the comparison flags.
- At the end of the block, it emits a
MASK_POPto wake up the ghost threads.
- It emits a
Now, I can write high-level massively-parallel code like this:
manifest pixel_base_addr = 0x1000;manifest thread_id = sys_get_tid(); // Resolves to hardwired ALU lane ID// The compiler maps these to physical registers (e.g. R0, R1)register current_pixel = load(pixel_base_addr + thread_id);register threshold = 128;// The compiler automatically emits CMP, MASK_PUSH and MASK_POP here!if (current_pixel > threshold) { current_pixel = 255; // White} else { current_pixel = 0; // Black}yeet current_pixel; // Emits data back to the DMA write-back queueMy Rust toolchain takes this syntax, compiles it down to .asm assembly, resolves all branch labels, assembles it into a raw .hex binary payload, and squirts it directly over the USB cable to the waiting FPGA.
Here is that whole journey for a single line of code — watch one expression fall all the way from text to the 16-bit words the silicon actually eats:
register y = a + b * c;
Part 5: Running the AI Model (Matrix Math on Silicon)
So, how do we actually run an AI model on this hardware? At its core, neural network inference is just a massive series of Matrix Multiplications and Activations (like ReLU). Here is exactly how we compute a Linear Layer (e.g., y = Wx + b).
1. The Setup (Data Loading)
First, the Host Laptop takes the compiled J++ binary, the input vector x, the Weight matrix W, and the biases b, and streams them all over USB. The DMA engine catches them and stores them in specific, known addresses in the 8 KB SRAM.
2. SIMT Dot Products
To compute the output, we need to multiply the input vector by the weight matrix. Instead of doing this sequentially, we use our SIMT architecture to do it in parallel.
The Dispatcher wakes up and launches a block of threads. Each thread uses its hardwired sys_get_tid() to determine which row of the weight matrix it is responsible for computing.
- Thread 0 is responsible for Output Neuron 0. It loads Row 0 of the weights.
- Thread 1 is responsible for Output Neuron 1. It loads Row 1 of the weights.
- Thread 2 is responsible for Output Neuron 2. It loads Row 2 of the weights.
All threads simultaneously execute a loop in lockstep. They fetch an input value, fetch their respective weight value, multiply them, and accumulate the sum in a local register (e.g., R0). Because the hardware supports Multi-Warp Latency Hiding, when Warp 0 stalls to wait for the weights to arrive from SRAM, Warp 1 instantly swaps in to compute its own dot products.
This is the multiply-accumulate (MAC) heart of the whole machine. Watch four lanes each grind out a separate output neuron from the same broadcast input, one cycle per element — the single loop that is a neural network layer:
x[0] and accumulates. Perfect SIMT lockstep.3. Non-Linearity (ReLU)
Once the loops finish, every thread adds its bias value. Then, we apply the ReLU activation function using branch divergence.
The compiled J++ code looks like this: if (neuron_sum < 0) { neuron_sum = 0; }. When the ALUs hit this instruction, threads with negative sums remain active and set their registers to 0. Threads with positive sums fail the condition, become "ghost threads," and skip the zeroing. When the block ends, the Reconvergence Stack wakes the ghost threads back up, and the warp continues.
4. Write-Back
Finally, every thread executes the yeet command (store). The LSU Arbiter takes the calculated output activations from the 4 threads and writes them safely back into the SRAM. The Host PC then reads the SRAM via USB, retrieving the model's predictions!
5. Did It Actually Work? (MNIST on Silicon)
This isn't a simulation-only party trick. I trained a small MNIST digit classifier, exported its weights and biases, and wrote the entire forward pass — the linear layers, the ReLU divergence, and the final argmax — in J++. My Rust compiler turned it into a hex payload, and the DMA engine streamed a real 28×28 handwritten digit into the FPGA's SRAM alongside the network.
Then the silicon ran. Pixels in one end of the USB cable, a single number out the other. The board took an image of a handwritten 7 and emitted the digit 7 — a full convolutional-style classifier, executing on 24 cents of logic gates I wired together myself, with no CPU, no operating system, and no framework anywhere in the loop. Just my ISA, my compiler, and my datapath. That was the moment the whole stack — from J++ syntax down to individual flip-flops — collapsed into a single working thing.
The Takeaway
Before this project, the gap between "code" and "computer" felt like magic. Now I know that a GPU is not a black box; it is just a brilliantly orchestrated factory. It is constrained by the physical limits of electricity, routing congestion, memory ports, and silicon space.
By stripping away the layers of abstraction and building the datapath from the ground up, I finally understand how modern AI accelerators pull off their magic.
If you want to see the Verilog, the Rust compiler, or run the simulation yourself, you can check out the full open-source project on GitHub!