# ESP32-S3-Matrix DQN Snake — A Verified C++ Port of a Full Reinforcement-Learning Stack

Most embedded Snake AI projects deploy a trained neural network and stop there. This project ports and verifies the entire reinforcement-learning decision stack from Python to bare-metal C++ on a [Waveshare ESP32-S3-Matrix](https://www.waveshare.com/esp32-s3-matrix.htm): a Dueling DQN, a body-hugging A* pathfinder used during state extraction, and a BFS/Hamiltonian survival shield that vetoes fatal actions.

The port runs without TensorFlow Lite Micro, ONNX Runtime, or any ML framework. Trained weights are compiled into flash-resident arrays and executed through a hand-written inference engine.

Rather than trusting a manual translation, a differential-testing harness ([`verification/`](verification/)) compares the C++ implementation against the original Python environment step-by-step, catching real discrepancies in pathfinding and tie-breaking behaviour before deployment.

The board also supports tilt-controlled manual play via its onboard QMI8658 6-axis IMU.

![DQN agent playing Snake autonomously on the ESP32-S3-Matrix's 8x8 LED display](assets/snake_AI_gif.gif)

## Highlights

- **Real on-device DQN inference** — a Dueling DQN (34 inputs → 256 → 256 → value/advantage heads → 3 Q-values) runs entirely on the ESP32-S3, no server, no Wi-Fi round-trip.
- **Bit-for-bit verified C++ port** — every part of the pipeline (34-feature state extraction, body-hugging A* pathfinder, BFS survival shield) is diffed against the real Python implementation using a differential-testing harness, not just hand-reviewed.
- **Retrained for the target hardware** — the source model trains on a large grid; this project retrains the same architecture at 8×8 to match the physical LED matrix, since a DQN's state features are scale-dependent.
- **Dual control modes** — autonomous AI play, or tilt-based manual control using the onboard QMI8658 accelerometer.
- **Runs on ~10% RAM, ~70% flash** of a 4MB ESP32-S3 — the entire trained network ships as flash-resident weight arrays, no external storage or model streaming required.

## Results

| Metric | Value |
|---|---|
| Input features | 34 |
| Network | Dueling DQN |
| Hidden layers | 256 → 256 |
| Output actions | 3 |
| Platform | ESP32-S3FH4R2 |
| RAM usage | ~10% |
| Flash usage | ~70% |
| ML runtime | None (hand-written C++ inference) |
| Verification method | Differential testing against the Python source |
| Verification coverage | 7,669 replayed real-gameplay steps, 0 mismatches |
| Training result | Best score 600/610 on the 8×8 grid (2,000 episodes) |

## Architecture

```mermaid
flowchart TD
    A["Snake state<br/>(body, direction, food)"] --> B["A* pathfinder<br/>(body-hugging)"]
    A --> C["34-feature state vector"]
    B --> C
    C --> D["Dueling DQN<br/>256 → 256 → value/advantage"]
    D --> E["Proposed action<br/>(3 Q-values)"]
    E --> F["Survival shield<br/>(BFS + Hamiltonian tiebreak)"]
    F --> G["Final action"]
    G --> H["LED matrix"]
```

## Hardware

| Component | Detail |
|---|---|
| Board | Waveshare ESP32-S3-Matrix (ESP32-S3FH4R2: 4MB flash, 2MB PSRAM) |
| Display | Onboard 8×8 addressable RGB LED matrix — `GPIO14` |
| IMU | QMI8658 6-axis accelerometer/gyroscope (I2C) — SDA `GPIO11`, SCL `GPIO12`, address `0x6B` |
| Connectivity | Native USB-Serial/JTAG (no external UART bridge) |

## Repository layout

```
firmware/                    PlatformIO project (Arduino framework)
  src/main.cpp                Game loop, LED rendering, tilt control, mode select
  src/ai_agent.cpp             Ported state extraction + A* + shield + DQN inference
  include/model_weights.h      Trained weights, exported as flash-resident C arrays
  include/ai_agent.h           Public interface: aiSelectAction(), aiOnNewGame()
  include/game_types.h         Shared, framework-agnostic types (Point, Direction, GRID)

verification/                 Differential test harness (see below)
  generate_golden_vectors.py   Captures ground truth from the real Python game/model
  test_state_extraction.cpp    Native C++ test: diffs the port against that ground truth
```

## How the Python model becomes C++ firmware

Deploying a trained PyTorch model to a microcontroller isn't just an export step — the model was trained inside a larger Python system (state featurization, a survival shield, an A* guidance signal) that all has to move to C++ *exactly*, or the network sees inputs it was never trained on.

**1. Retrain for the target grid.** [DQN-AI-Snake](https://github.com/GavinnnTann/DQN-AI-Snake) trains on a large grid by default. Since several of the 34 input features (wall distances, available free space, food distance) are normalized relative to grid size, a model trained at one scale doesn't transfer cleanly to an 8×8 board — the feature *distributions* shift, not just their scale. The same training code is re-run with the grid size parameterized down to 8×8, producing a checkpoint (`.pth`) purpose-fit for this hardware.

**2. Export weights to flash-resident C arrays.** A small export script reads the trained `state_dict` directly out of the PyTorch checkpoint — the weight and bias matrices for the Dueling DQN's six linear layers (shared trunk, value head, advantage head) — and writes them as `static const float[]` arrays into a generated C header. No ONNX, no TensorFlow Lite Micro runtime: just flat arrays the ESP32-S3's compiler places in flash and a hand-written forward pass reads directly.

**3. Port the surrounding Python logic to C++, line-for-line.** The trained network never acts alone — Python wraps it in a 34-feature state extractor (danger detection, wall/food distances, a body-hugging A* pathfinder used as one of the input features) and a survival shield (BFS reachability + a Hamiltonian-cycle tiebreak) that vetoes any move the network proposes if it would trap the snake. All of it — including the A* algorithm's tie-breaking priority queue — is reimplemented in C++ to match the Python semantics exactly, since even subtle differences (like priority-queue tie-break order) change which paths get chosen.

**4. Verify the port against the source, not against intuition.** A differential-testing harness drives the *real* Python `GameEngine`, feeds states through the *real* trained model, and records the exact state vectors, Q-values, and shield decisions produced at every step of real gameplay. The C++ port replays those same recorded episodes and diffs its output against that ground truth, feature-by-feature, decision-by-decision. This caught two real porting bugs — a stale-buffer issue in the A* backtrack and a priority-queue tie-break mismatch — that hand-review had missed. See [`verification/README.md`](verification/README.md) for how to reproduce it.

**5. Run it.** `aiSelectAction()` ties it together on-device: build the 34-feature state → run the ported forward pass → let the ported shield pick the safest, highest-preference move → apply it to the LED matrix, every game tick.

## Building and flashing

```bash
cd firmware
pio run                              # build
pio run --target upload              # flash (auto-detects the board's USB-Serial/JTAG port)
pio device monitor                   # view serial output
```

Build-time flags in `main.cpp` select the mode:

| Flag | Effect |
|---|---|
| `AI_MODE` | Trained DQN + survival shield plays autonomously (default) |
| `CALIBRATION_MODE` | Live tilt visualizer for verifying IMU axis orientation |
| `CORNER_TEST_MODE` | Static 4-corner color test for verifying LED pixel addressing |

## Related work

**[DQN-AI-Snake](https://github.com/GavinnnTann/DQN-AI-Snake)** ([@GavinnnTann](https://github.com/GavinnnTann)) — the training-side sibling of this repo. Model architecture, curriculum learning, and the full desktop Snake environment live there; this repo is its embedded C++ deployment target.

**[NeuroSnake](https://www.rebels.software/blog/neurosnake-when-tinyml-meets-classic-gaming-in-a-snake-shaped-pcb-2025)** (Rebels.Software, 2025) — a similarly-scoped project: a DQN trained in Python/TensorFlow deployed to a microcontroller (Nordic nRF54L15) to play Snake on a badge-shaped PCB. The difference is mainly scope and verification: NeuroSnake ships an 11-feature DQN via TensorFlow Lite Micro, with the learned policy as the only thing standing between the snake and a wall. This project's network gets help from an A*-guided state feature and a survival shield that formally vetoes fatal moves, runs inference without any ML runtime, and has its entire C++ port verified against the Python source with a differential-testing harness rather than trusted on inspection. NeuroSnake's write-up doesn't link public code, so this repo — firmware and verification harness both public — may be a useful reference implementation for a similar build.

## License

[MIT](LICENSE)

## Keywords

ESP32-S3, DQN, Deep Q-Network, Dueling DQN, reinforcement learning, Snake game AI, embedded machine learning, on-device inference, TinyML, LED matrix, QMI8658, IMU tilt control, PlatformIO, Arduino, Waveshare ESP32-S3-Matrix, C++ model port, PyTorch to embedded C++.
