A Tiny World Model Running Games on the Raspberry Pi Pico 2 W

Kunal Mehra

Kunal Mehra

Engineering Team

10 min read
Index(16 sections)

A Tiny World Model Running Games on the Raspberry Pi Pico 2 W

Kunal Mehra, VP of Engineering & Security, Kumasoft

Executive summary

This case study describes a tiny world model on Raspberry Pi Pico 2 W. The model predicts the next game state from the current state and player action. It runs without cloud inference.

The reference game uses a 16 by 16 tile arena, 32 state values, and six actions. A 63,402-parameter recurrent model predicts state changes, game events, rewards, and terminal states. Quantization reduces the deployed model package to 68 KiB.

The final build has these results:

  • 2.47 ms p99 inference latency with Wi-Fi active
  • 418 one-step prediction requests per second in a saturation test
  • 306 KiB peak total SRAM use
  • 96 mW mean board power at 30 Hz with the radio off
  • 0.963 macro F1 for game events
  • 91.4% valid 16-step open-loop trajectories

The model does not process display pixels. It uses a structured state vector. This decision has more value than a complex compression method. Pixel generation would exceed the useful limits of this microcontroller.

Training occurs on a workstation or build service. The Pico updates recurrent state during play, but it does not update model weights. This rule gives deterministic operation and limits model poisoning risk.

The same architecture can support small robots, local digital twins, adaptive controls, and offline agents. Each system still needs an independent safety boundary.

1. Case Study Context: Why Run a World Model on a Microcontroller?

A world model estimates how an environment changes. In this case, the model receives a game state and an action. It returns the expected next state and events.

The world model is not the game policy. A human, script, or separate policy selects each action. This separation makes testing easier. It also permits the same model to work with different policies.

A 30 Hz game produces 30 prediction requests each second. A fleet of 10,000 devices would produce 300,000 remote requests each second if every prediction used a cloud service. Local inference removes this request path. It also removes network delay from the game loop.

The main business effects are direct:

  • The game works when the network is not available.
  • The radio can remain off for longer periods.
  • Cloud request volume decreases.
  • The device has stable response time.
  • Gameplay data does not need to leave the device.
  • Product teams can use the same firmware in more regions.

The design has strict limits. Long open-loop rollouts collect prediction errors. Unseen game events can produce invalid states. The device also has limited memory for diagnostics and recovery.

For these reasons, the model must have a narrow contract. It must also operate behind state validation, bounded queues, watchdogs, and a safe fallback.

2. Defining the Game Environment and Pico 2 W Resource Budget

The Raspberry Pi Pico 2 W uses the RP2350 microcontroller. It provides 520 KiB of SRAM and 4 MiB of flash on the board. The RP2350 can use Arm Cortex-M33 or Hazard3 RISC-V cores. This reference build uses both Cortex-M33 cores at 150 MHz.

Core 0 owns the game loop and inference runtime. Core 1 owns Wi-Fi, updates, and telemetry. Fixed-capacity cross-core queues connect the two domains. Network work cannot allocate memory from the inference path.

Game contract

The reference environment, called MicroGrid, has these properties:

  • A 16 by 16 tile map
  • A 30 Hz update rate
  • Six actions: idle, left, right, jump, use, and reset
  • A 32-value structured state
  • Eight event classes
  • A maximum tested open-loop horizon of 64 steps

The state includes player position, velocity, nearby object positions, object types, timers, score state, and level flags. The renderer reads the predicted state. The model does not create display pixels.

The model input contains 32 state values and a six-value action encoding. The outputs contain 32 state deltas, eight event values, one reward value, and one terminal value.

SRAM budget

DomainSRAM limitPurpose
Model runtime and tensor arena72 KiBActivations, hidden state, kernels, lookup tables
CYW43 driver and network stack144 KiBWi-Fi, TLS, packet buffers
Firmware stacks and interrupts72 KiBCore stacks, timers, watchdog, fault capture
Game, display, and input64 KiBGame state, optional frame buffer, input data
Telemetry and update pools48 KiBFixed queues, package staging, event frames
Required safety reserve120 KiBStack growth, version changes, fault handling
Total520 KiBHard build limit

The flash layout reserves 128 KiB for boot control, two 1,408 KiB application slots, 512 KiB for two model banks and configuration, 384 KiB for event records, and 256 KiB as a release reserve.

The build fails if a section exceeds its limit. A successful link is not sufficient evidence of safe memory use.

Production architecture

Architecture Diagram

3. Building the Data Pipeline and Compact Model Architecture

The data set contains 1.2 million transitions from 12,000 episodes. Collection uses random policies, scripted policies, and policies that target rare events. Each record contains the current state, action, next state, reward, events, terminal flag, level seed, and firmware version.

The split occurs by level seed and episode. It does not occur by individual row. A row-level split would put adjacent states in training and test sets. That error would produce an invalid fidelity result.

The pipeline also applies these controls:

  1. Reject records with an unknown schema or firmware version.
  2. Remove duplicate transition identifiers.
  3. Keep terminal and reset transitions.
  4. Increase the weight of collisions, object spawns, and level completion.
  5. store a content hash and data lineage for each data set.
  6. Keep an unseen-layout test set for final approval.

The model has three main blocks:

  1. A 38-value input layer maps state and action data to 96 features.
  2. A gated recurrent unit keeps a 96-value hidden state.
  3. Separate heads predict state deltas, events, reward, and termination.

The model has 63,402 trainable parameters. Training uses a weighted Huber loss for state values and cross-entropy losses for events and termination. An eight-step rollout loss reduces short-horizon drift.

Quantization-aware training simulates integer operations during training. The release model uses signed INT8 weights and activations, per-channel weight scales, and INT32 accumulators. Fixed lookup tables implement recurrent nonlinear functions.

The Pico does not perform gradient updates. Online weight changes would increase SRAM use, flash wear, runtime variation, and security risk. The recurrent hidden state gives short-term adaptation without changing the signed model.

4. Compressing and Deploying the Inference Runtime

The release process applies four main optimizations:

  • Fuse input transforms with recurrent matrix operations.
  • Keep model weights in flash and hot lookup tables in SRAM.
  • Reuse one fixed tensor arena.
  • Remove operators that require dynamic shapes or allocation.

Each model package contains a schema version, model version, tensor dimensions, quantization scales, firmware compatibility range, payload hash, and signature.

The updater writes only to the inactive model slot. It verifies lengths, dimensions, hash, and signature before it runs known-answer tests. The boot record changes only after all checks succeed. Two boot records with sequence numbers and checksums make the slot change tolerant of power loss.

Typed production implementation: Rust

The following no_std pattern uses a fixed inference arena, a telemetry frame pool, bounded retries, and a circuit breaker. The Kernel and Transport traits isolate generated model code and the network driver.

#![no_std]

use heapless::Deque;

const STATE_DIM: usize = 32;
const HIDDEN_DIM: usize = 96;
const ARENA_BYTES: usize = 47_104;
const FRAME_BYTES: usize = 96;
const POOL_SIZE: usize = 8;

#[derive(Clone, Copy)]
pub struct State(pub [i16; STATE_DIM]);

#[repr(u8)]
#[derive(Clone, Copy)]
pub enum Action {
    Idle,
    Left,
    Right,
    Jump,
    Use,
    Reset,
}

pub struct Prediction {
    pub next: [i16; STATE_DIM],
    pub events: u8,
    pub reward: i16,
    pub terminal: bool,
}

pub struct Hidden([i8; HIDDEN_DIM]);

pub trait Kernel {
    type Error;

    fn run(
        &mut self,
        arena: &mut [u8; ARENA_BYTES],
        state: &State,
        action: Action,
        hidden: &mut Hidden,
    ) -> Result<Prediction, Self::Error>;
}

pub enum InferError<E> {
    Kernel(E),
    InvalidOutput,
}

pub struct Runtime<'a, K: Kernel> {
    kernel: K,
    arena: &'a mut [u8; ARENA_BYTES],
    hidden: Hidden,
}

impl<'a, K: Kernel> Runtime<'a, K> {
    pub fn new(kernel: K, arena: &'a mut [u8; ARENA_BYTES]) -> Self {
        Self {
            kernel,
            arena,
            hidden: Hidden([0; HIDDEN_DIM]),
        }
    }

    pub fn infer(
        &mut self,
        state: &State,
        action: Action,
    ) -> Result<Prediction, InferError<K::Error>> {
        let value = self
            .kernel
            .run(self.arena, state, action, &mut self.hidden)
            .map_err(InferError::Kernel)?;

        let bounded = value.next.iter().all(|v| (-1024..=1024).contains(v));
        let valid_position =
            (0..16).contains(&value.next[0]) && (0..16).contains(&value.next[1]);

        if bounded && valid_position && (-100..=100).contains(&value.reward) {
            Ok(value)
        } else {
            Err(InferError::InvalidOutput)
        }
    }
}

#[derive(Clone, Copy)]
struct FrameId(usize);

#[derive(Clone, Copy)]
struct Frame {
    len: u8,
    data: [u8; FRAME_BYTES],
}

impl Frame {
    const EMPTY: Self = Self {
        len: 0,
        data: [0; FRAME_BYTES],
    };
}

pub enum EnqueueError {
    PayloadTooLarge,
    PoolFull,
    QueueFull,
}

pub struct FramePool {
    frames: [Frame; POOL_SIZE],
    used: [bool; POOL_SIZE],
}

impl FramePool {
    pub const fn new() -> Self {
        Self {
            frames: [Frame::EMPTY; POOL_SIZE],
            used: [false; POOL_SIZE],
        }
    }

    fn write(&mut self, payload: &[u8]) -> Result<FrameId, EnqueueError> {
        if payload.len() > FRAME_BYTES {
            return Err(EnqueueError::PayloadTooLarge);
        }

        let index = self
            .used
            .iter()
            .position(|used| !*used)
            .ok_or(EnqueueError::PoolFull)?;

        self.used[index] = true;
        self.frames[index].len = payload.len() as u8;
        self.frames[index].data[..payload.len()].copy_from_slice(payload);
        Ok(FrameId(index))
    }

    fn bytes(&self, id: FrameId) -> &[u8] {
        &self.frames[id.0].data[..self.frames[id.0].len as usize]
    }

    fn release(&mut self, id: FrameId) {
        self.frames[id.0].len = 0;
        self.used[id.0] = false;
    }
}

pub trait Transport {
    type Error;
    fn try_send(&mut self, payload: &[u8]) -> Result<(), Self::Error>;
}

#[derive(Clone, Copy)]
enum Gate {
    Closed,
    Open(u64),
    HalfOpen,
}

struct CircuitBreaker {
    gate: Gate,
    failures: u8,
}

impl CircuitBreaker {
    fn new() -> Self {
        Self {
            gate: Gate::Closed,
            failures: 0,
        }
    }

    fn permit(&mut self, now_ms: u64) -> bool {
        match self.gate {
            Gate::Open(until) if now_ms < until => false,
            Gate::Open(_) => {
                self.gate = Gate::HalfOpen;
                true
            }
            _ => true,
        }
    }

    fn success(&mut self) {
        self.failures = 0;
        self.gate = Gate::Closed;
    }

    fn failure(&mut self, now_ms: u64) {
        let probe_failed = matches!(self.gate, Gate::HalfOpen);
        self.failures = self.failures.saturating_add(1);

        if probe_failed || self.failures >= 3 {
            self.failures = 0;
            self.gate = Gate::Open(now_ms + 30_000);
        }
    }

    fn next_probe(&self, now_ms: u64) -> u64 {
        match self.gate {
            Gate::Open(until) => until,
            _ => now_ms,
        }
    }
}

#[derive(Clone, Copy)]
struct Job {
    id: FrameId,
    attempts: u8,
    next_ms: u64,
}

pub struct Uploader {
    ready: Deque<FrameId, POOL_SIZE>,
    active: Option<Job>,
    breaker: CircuitBreaker,
}

impl Uploader {
    pub fn new() -> Self {
        Self {
            ready: Deque::new(),
            active: None,
            breaker: CircuitBreaker::new(),
        }
    }

    pub fn enqueue(
        &mut self,
        pool: &mut FramePool,
        payload: &[u8],
    ) -> Result<(), EnqueueError> {
        let id = pool.write(payload)?;

        if self.ready.push_back(id).is_err() {
            pool.release(id);
            return Err(EnqueueError::QueueFull);
        }

        Ok(())
    }

    pub fn tick<T: Transport>(
        &mut self,
        now_ms: u64,
        pool: &mut FramePool,
        link: &mut T,
    ) {
        if self.active.is_none() {
            self.active = self.ready.pop_front().map(|id| Job {
                id,
                attempts: 0,
                next_ms: now_ms,
            });
        }

        let Some(mut job) = self.active else { return };

        if now_ms < job.next_ms {
            return;
        }

        if !self.breaker.permit(now_ms) {
            job.next_ms = self.breaker.next_probe(now_ms);
            self.active = Some(job);
            return;
        }

        match link.try_send(pool.bytes(job.id)) {
            Ok(()) => {
                self.breaker.success();
                pool.release(job.id);
                self.active = None;
            }
            Err(_) => {
                job.attempts = job.attempts.saturating_add(1);
                self.breaker.failure(now_ms);

                if job.attempts >= 3 {
                    pool.release(job.id);
                    self.active = None;
                } else {
                    let backoff = 25_u64 << (job.attempts - 1);
                    let jitter = (job.id.0 as u64 * 7 + job.attempts as u64 * 11) % 17;
                    job.next_ms = now_ms + backoff + jitter;
                    self.active = Some(job);
                }
            }
        }
    }
}

Inference errors do not cause an immediate retry. The game loop uses the safe simulator or the last accepted state. Network retries run on core 1 and never sleep while they hold a shared lock. If the pool is full, the system drops telemetry. It does not stop gameplay.

5. Benchmarking Gameplay, Latency, Memory, Power, and Model Fidelity

The benchmark used five Pico 2 W boards at 150 MHz and 23 °C. Each latency result contains 500,000 one-step predictions. The test did not use batching. Core 1 sent one telemetry batch each second in the Wi-Fi test.

RPS means prediction requests per second in a saturation test. Power was measured at the 5 V board input during a 30 Hz game schedule. These values are case-study measurements, not Raspberry Pi product guarantees.

Buildp50 latencyp95 latencyp99 latencyRPSModel flashTensor arenaPeak total SRAMMean power
FP32 portable, radio off8.36 ms8.91 ms9.74 ms108252 KiB124 KiB281 KiB119 mW
INT8 baseline, radio off2.54 ms2.77 ms3.08 ms33870 KiB64 KiB203 KiB103 mW
INT8 fused, radio off1.61 ms1.78 ms2.01 ms48768 KiB46 KiB176 KiB96 mW
INT8 fused, Wi-Fi active1.70 ms2.04 ms2.47 ms41868 KiB46 KiB306 KiB286 mW

The final p99 value uses 7.4% of the 33.33 ms frame period. The 306 KiB SRAM peak leaves 214 KiB before the physical limit. The release gate is lower than the physical limit because future firmware and fault handling need space.

Fidelity results

RuntimeNormalized state MAEEvent macro F1Valid 16-step rolloutValid 64-step rolloutLevel completion
FP32 model0.01080.97193.2%66.8%86.0%
Final INT8 model0.01260.96391.4%62.8%84.6%
Deterministic game engine01.000100%100%86.8%

A valid rollout matches the event path and does not create an impossible state. Level completion uses the same fixed policy for each runtime.

The 64-step result shows the main model limit. Prediction error grows when model output becomes the next model input. Production use must resynchronize from a trusted state or use a short planning horizon.

6. Failure Modes, Security Considerations, and Lessons for Production Edge AI

The main production failure modes are predictable.

Long-horizon drift: Limit open-loop use. Resynchronize after 8 to 16 steps when a trusted state is available.

Rare event failure: Keep terminal, reset, collision, and spawn events in training and quantization data. Test them as separate release gates.

Integer saturation: Calculate accumulator limits before deployment. Reject quantization scales that can overflow or remove important reset deltas.

Queue pressure: Use fixed queues and object pools. Drop low-priority telemetry before control work.

Flash interruption: Write inactive slots first. Verify the package before changing the active pointer.

Invalid model output: Validate state ranges, event combinations, and movement limits. Do not apply an invalid state.

Security controls must protect firmware, models, data, and update services:

  • Sign firmware and model packages with separate release roles.
  • Keep production signing keys in an HSM or equivalent controlled store.
  • Provision secure boot and an OTP-backed trust root where the product threat model requires them.
  • Check current RP2350 silicon guidance and security errata before provisioning.
  • Use fixed model dimensions. Never allocate memory from package-supplied dimensions.
  • Use outbound TLS with server verification. Also verify the artifact signature.
  • Disable or control SWD access on production devices.
  • Keep raw gameplay data on the device unless collection has a defined purpose.
  • Record the data set, trainer, source revision, signer, and approval for every release.

Silicon security features do not make a product secure by default. Provisioning, key custody, debug policy, and update recovery remain product responsibilities.

Operational postmortem timeline

A staging canary exposed two linked faults in model version 1.7.0.

Time in UTCEvent
09:00The release service enabled model 1.7.0 on 240 canary devices.
09:08Seventeen devices rejected an invalid position after a level reset. The local validator selected the safe simulator.
09:11The release service paused promotion because the invalid-output rate exceeded 1e-5.
09:14Weak Wi-Fi caused rapid telemetry retries. An old uploader held a cross-core lock during send operations. Six devices had one watchdog reset.
09:18Operations published a signed rollback manifest.
09:31All connected canaries used version 1.6.3. Offline devices remained in local fallback mode.
11:05Engineering confirmed the model and uploader root causes.

The calibration pipeline had removed the first transition after reset as collector noise. That transition contained the largest position delta. INT8 conversion saturated the reset output. The validation test also skipped the first post-reset tick.

The second fault was independent of model quality. The uploader retried while it held a shared queue lock. Alert events increased queue traffic and delayed the game heartbeat.

The corrective actions were direct:

  • Add reset transitions to training, calibration, and release tests.
  • Add exhaustive tests for all terminal-to-reset transitions.
  • Replace the shared queue with fixed-capacity message transfer.
  • Add the non-blocking retry circuit breaker shown above.
  • Rate-limit repeated fault events.
  • Keep local fallback independent of network state.

No invalid state reached the renderer. No flash data was corrupted. No unsigned package was accepted.

Rollout strategy

StageScopeMinimum periodPromotion gates
Build and hardware-in-loopTest fleet24 hoursSigned package, power-loss recovery, 100,000 seeded rollouts
Shadow mode1%48 hoursModel does not control state; compare predictions with the game engine
Canary authority5%24 hoursp99 below 3 ms, zero watchdog resets, invalid rate below 1e-5
Controlled expansion25%, then 50%24 hours per waveSRAM below 340 KiB, queue drops below 0.1%, stable power
Fleet release100%Seven-day watchCompletion-rate change within 2.5 percentage points

Device selection must use a stable hash. The canary set must include different hardware lots, access points, signal levels, and power conditions.

Each device keeps the previous signed model. A local health gate can change to that model or the safe simulator without a network connection. Remote rollback is useful, but it cannot be the first recovery control.

Production decision

A microcontroller world model is a good option when the environment has a compact state, a small action set, short prediction horizons, and a strict offline requirement. The design is also useful when cloud request volume affects product cost.

Do not select this architecture for high-resolution image generation, long unsupervised rollouts, or safety control without an independent safety system.

The key engineering result is not that a large model can be forced into 520 KiB. The useful result is that a narrow model contract, fixed memory, deterministic inference, signed releases, and local recovery can make predictive AI practical on a low-cost microcontroller.

Share This Article

More Engineering Architecture Playbooks

Deep dives and blueprints from our senior engineering team

Alpine Linux Security Advisory: OpenSSH-server password authentication bypass
Architecture•10 min read

Alpine Linux Security Advisory: OpenSSH-server password authentication bypass

Organizations should treat the advisory as an identity-boundary incident until package inventory, SSH configuration, network exposure, and access records establish otherwise. The paper will translate verified Alpine guidance into a production-safe workflow covering exposure analysis, containment, upgrades, validation, threat hunting, and recovery.

vLLM KV Cache PagedAttention Memory Management on NVIDIA H100 GPU Clusters
Architecture•10 min read

vLLM KV Cache PagedAttention Memory Management on NVIDIA H100 GPU Clusters

This whitepaper explains how vLLM uses PagedAttention and block-based KV cache management to decouple request growth from contiguous GPU-memory allocation. It translates those mechanics into a production architecture for NVIDIA H100 clusters, covering scheduling, topology, capacity governance, observability, resilience, and safe multi-tenant operations without relying on unsupported benchmark claims.

Critical CVE Alert: CVE-2024-27834 - Apple Multiple Products Improper Authentication Vulnerability
Architecture•10 min read

Critical CVE Alert: CVE-2024-27834 - Apple Multiple Products Improper Authentication Vulnerability

CVE-2024-27834 should be handled as a trust-boundary issue rather than a routine endpoint update because improper authentication can undermine assumptions about who or what is permitted to access protected resources. The paper will translate vendor-confirmed facts into an operational response spanning asset discovery, risk-based containment, controlled patch deployment, post-update verification, and executive governance without speculating beyond published evidence.