Skip to content

About

Four-tier autonomous brain for the Pollen Robotics Microduck / Open Duck Mini 14-DOF biped: stateless intent parser, hysteresis world state, reactive behavior tree, MuJoCo sim-to-real, and real-time ONNX motor daemon.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Microduck Robot Brain

CI Python 3.11+ C++20 RT MuJoCo 3+ License: Apache-2.0

Microduck Robot Brain (DuckBrain) separates high-level stateless intent parsing, reactive behavior planning, and low-level 50 Hz neural motor policy execution for the Pollen Robotics Microduck 14-DOF biped. Motor control, RL locomotion policies, and hardware safety run inside robotd; DuckBrain selects what to do, tracks targets via closed-loop visual servoing, and streams live telemetry to an offline-ready web cockpit.

Microduck 50 Hz MuJoCo simulation with DuckBrain HUD

Why small transformers fail in motor loops

Placing a small (<100 MB, 50M to 100M parameter) sequence model in a closed motor loop creates distinct failure modes:

  1. Dynamic replanning vs open-loop generation. An autoregressive sequence like SEARCH -> APPROACH -> PICKUP creates an open-loop token chain. If the target rolls away during approach, the sequence invalidates. Sampling every frame causes policy chattering at state boundaries.
  2. Token hallucination and precondition violations. Small models lack physical grounding. A 50M model will generate PICKUP when an object is not visible simply because the user prompt contained "fetch the ball".
  3. Sensor noise and attention resets. Bipedal walking creates IMU vibration and camera bounce. Noisy boolean tokens reset attention weights and cause abandoned tasks.
  4. Compute contention. At <100 MB, models lack emergent reasoning yet compete with 50 to 100 Hz motor loops for memory bus bandwidth and CPU caches.
  5. Long-horizon drift. Ongoing autoregressive execution bloats KV caches and drifts into repetitive action loops.

The architecture solves this by restricting the Transformer to one-shot speech parsing at the user boundary, delegating reactive execution to a Behavior Tree, and running motor policies inside an isolated real-time daemon.

Four-tier pipeline

flowchart TD
    U["Speech / Natural-Language Input"] --> T1
    T1["Tier 1: Stateless Intent Extraction<br/>One-shot JSON goal parser (zero ongoing KV cache)"] -->|"ParsedIntent"| T2
    T2["Tier 2: WorldState Sanitization (10–20 Hz)<br/>Schmitt trigger hysteresis, temporal debouncing, 8x8 ToF & SORT visual track"] -->|"Debounced tokens"| T3
    T3["Tier 3: Reactive Behavior Tree (10–20 Hz)<br/>Visual servoing, asymmetric ambient blending & stability-gated expressions"] -->|"Kinematic cmd (vx, vy, wz, head)"| T4
    T4["Tier 4: robotd Real-Time Execution (50–100 Hz)<br/>Core-pinned SCHED_FIFO, lock-free POSIX SeqLock, 61D ONNX policy -> 14 XL330 servos"]
    T2 -.->|"10 Hz SSE telemetry"| DASH["Live Web Telemetry & Command Cockpit<br/>8x8 ToF heatmap · BAM M6 sag · 1-click skills · E-STOP"]
    DASH -.->|"POST /api/command"| T1
Loading

Tier 1: Stateless intent extraction

Runs once per command string. It outputs a typed goal and exits:

{
  "action": "FETCH",
  "target": "ball",
  "urgency": "MEDIUM"
}

The model maintains no ongoing KV cache.

Tier 2: WorldState sanitization

Converts continuous noisy sensor data into stable discrete tokens:

  • Schmitt trigger hysteresis: IMU pitch and roll variance transitions to LOW stability above 0.65 rad/s^2, returning to HIGH only after falling below 0.35 rad/s^2.
  • Temporal debouncing: Vision detections require positive identification in 7 of the last 10 frames before asserting visibility.

Tier 3: Reactive behavior tree

Manages task progression and body language:

  • Sequential actions: Steps through Search, Approach, Pickup, and Return.
  • Asymmetric parallel node: Ticks locomotion while running ambient head scanning. If stability drops, scanning offsets clamp to zero.
  • Failure expressions: Single failures trigger an inquisitive head tilt. Three consecutive failures trigger a head shake. If balance drops, expressions are suppressed.

Tier 4: robotd and motor execution

Communicates with Tier 3 over lock-free POSIX shared memory (SeqLockChannel) with single-digit nanosecond latency.

  • Process isolation: Core 4 dedicated to the 50 to 100 Hz loop via SCHED_FIFO priority 99.
  • Attitude command filter: Clamps body lean rate of change to 0.5 rad/s and attenuates lean to zero as forward speed approaches 0.8 m/s.
  • Locomotion policy: 61D observation vector feeds an ONNX actor network, commanding 14 joint PD targets across legs and neck.

1080P Full HD demonstration video

DuckBrain includes a 1080P (1920x1080 @ 30 FPS) physics demonstration video rendered in MuJoCo (output/microduck_brain_demo_1080p.mp4) with live 50 Hz sim-to-real telemetry HUD and synchronized audio:

  1. Scene 1: Multi-modal intent & ToF environmental scan (0:00-0:08). "Ducky, navigate the maze, retrieve the marker, and drop it in the tray!" parsed via stateless one-shot extractor. 8x8 matrix ToF active depth scan with 64 color-coded live cells on HUD.
  2. Scene 2: Ground crouch retrieval with zero floor penetration (0:08-0:16). Ground approach and authentic bipedal squat derived from Pollen Robotics official alpha_ground_pick.onnx policy kinematics with foot soles strictly flat on the floor ($z_{\text{foot}} \ge 0.000,\text{m}$, zero warping), and $C^2$ quintic smoothstep transitions.
  3. Scene 3: Articulated beak clamp & counterbalanced payload lift (0:16-0:24). Authentic Pollen lower jaw articulates open to $28,\text{mm}$ aperture ($0.35,\text{rad}$), clamps firmly on $14,\text{mm}$ dry-erase marker with active collision geometry, and lifts to full upright stance with dynamic center-of-mass counterbalancing and BAM M6 battery voltage sag telemetry.
  4. Scene 4: Desktop maze chicane navigation with real-time ToF avoidance (0:24-0:32). Navigates a staggered 2-wall desktop wooden maze chicane with real-time 8x8 ToF obstacle proximity steering and living anticipatory head yaw saccades into upcoming turns.
  5. Scene 5: Shallow transparent container arrival & marker drop-off (0:32-0:40). Terminal arrival at shallow acrylic container ($12,\text{mm}$ clear rim), forward bowing posture over target, beak opens to $28,\text{mm}$, and marker settles naturally under gravity ($g = -9.81,\text{m/s}^2$) with a plastic drop acoustic click.
  6. Scene 6: Celebratory tilt, cheerful quack & seated rest (0:40-0:48). Expressive $+14^\circ$ inquisitive head roll celebration tilt, nod, cheerful vocal quack, and smooth descent into seated rest posture. Unanimously certified zero falls across all 1,440 frames, 100% factory XL330 Dynamixel limits observed, all 5 evaluation benchmarks passed.

Render locally with:

python scripts/render_demo_video.py

See docs/demo_video.md for full scene breakdown and parameters.

Repository layout

microduck-robot-brain/
├── CMakeLists.txt              # C++20 build config for robotd and bt_bridge
├── include/
│   ├── duck_shm.hpp            # Aligned shared memory structs and SeqLock
│   └── shm_client.hpp          # POSIX shm manager with Windows fallback
├── src/
│   ├── robotd_main.cpp         # 50 Hz real-time motor daemon
│   └── bt_bridge_node.cpp      # 20 Hz Behavior Tree IPC client
├── microduck_brain/            # Python core package
│   ├── intent_parser.py        # Stateless goal extractor
│   ├── world_state.py          # Schmitt triggers and debouncers
│   ├── logit_masking.py        # Precondition logit masking
│   ├── skill_latch.py          # Asynchronous skill latching
│   ├── behavior_tree.py        # BT nodes and expression logic
│   ├── locomotion_engine.py    # Attitude filter and ONNX runner
│   ├── pollen_bridge.py        # IPC client for Pollen robotd socket
│   └── sim/                    # Sim-to-real MuJoCo physics stack
│       ├── mjcf/               # Self-contained Microduck XML models
│       ├── bam_actuator.py     # BAM M6 DC motor & battery sag model
│       ├── backlash.py         # Mechanical backlash twin dynamics
│       ├── env.py              # Gym environment with 61D contract
│       └── train_smoke.py      # Local PyTorch PPO training runner
├── isaac_lab/
│   ├── env_cfg.py              # Isaac Lab RL config with domain randomization
│   └── export_onnx.py          # ONNX model exporter
├── systemd/
│   ├── robotd.service          # Real-time systemd service unit
│   ├── realtime.slice          # Cgroup v2 slice for Core 4
│   └── 10-cpu-affinity.conf    # System-wide CPU shielding
├── sysctl/
│   └── 99-realtime.conf        # Kernel latency tuning
├── scripts/
│   ├── shield_rt_cores.sh      # IRQ affinity steering script
│   ├── plot_latency.py         # Cyclictest latency distribution plotter
│   ├── run_simulation.py       # End-to-end multi-tier simulation demo
│   └── run_mujoco_sim.py       # Behavior Tree MuJoCo sim runner
└── tests/                      # Pytest unit & integration test suite

Live web telemetry & command cockpit

Launch the zero-dependency HTTP + Server-Sent Events cockpit (microduck_brain/dashboard.py, stdlib-only so it runs out of the box on Raspberry Pi CM4 with no web framework dependencies) alongside either the physical robot or MuJoCo simulation:

# Physical robot (or --dry-run offline test) with live cockpit at http://127.0.0.1:8765
microduck-run --dry-run --interactive --dashboard

# Headless MuJoCo simulation with live cockpit
microduck-sim --steps 500 --onnx models/microduck_walk.onnx --dashboard

Microduck DuckBrain live web telemetry cockpit

Quick start

Python package and tests

Install lightweight core runtime (ideal for Raspberry Pi CM4 onboard deployment without PyTorch/MuJoCo):

pip install -e .

Or install the full simulation, vision, and test stack:

pip install -e ".[dev]"

Run tests:

python -m pytest tests/ -v

CLI entrypoints installed with the package:

microduck-sim --steps 250 --onnx models/microduck_walk.onnx --headless
microduck-eval
microduck-check --dry-run
microduck-run --interactive --dashboard

Build C++ real-time daemon

mkdir build && cd build
cmake ..
cmake --build . --config Release

Run daemon and bridge:

# Terminal 1: Real-time motor daemon (run with RT priority on Linux)
./robotd

# Terminal 2: Behavior tree bridge node
./bt_bridge_node

Real-time Linux kernel setup

  1. Copy kernel sysctl configuration:
sudo cp sysctl/99-realtime.conf /etc/sysctl.d/
sudo sysctl --system
  1. Configure systemd CPU shielding and real-time slice:
sudo cp systemd/10-cpu-affinity.conf /etc/systemd/system.conf.d/
sudo cp systemd/realtime.slice /etc/systemd/system/
sudo cp systemd/robotd.service /etc/systemd/system/
sudo systemctl daemon-reload
  1. Mask hardware IRQs away from Core 4:
sudo chmod +x scripts/shield_rt_cores.sh
sudo ./scripts/shield_rt_cores.sh
  1. Boot kernel flags in /etc/default/grub:
GRUB_CMDLINE_LINUX_DEFAULT="... isolcpus=4 nohz_full=4 rcu_nocbs=4"

Run sudo update-grub and reboot.

  1. Start robotd service:
sudo systemctl enable --now robotd.service

Latency verification

Verify scheduling latency under stress using cyclictest:

# Terminal 1: Background load on housekeeping cores (0-3, 5-7)
sudo stress-ng --taskset 0-3,5-7 --cpu 7 --vm 2 --vm-bytes 1G --io 4 --timeout 10m

# Terminal 2: Measurement thread on Core 4
sudo cyclictest --mlockall --priority=99 --affinity=4 --mainaffinity=0 \
  --threads=1 --interval=200 --duration=10m --histogram=100 --histfile=latency_hist.txt

Plot results:

python scripts/plot_latency.py latency_hist.txt

Sim-to-real MuJoCo pipeline

Pollen Robotics trains Microduck locomotion and recovery behaviors in MuJoCo and deploys identical weights directly to physical bipeds. The framework bridges the reality gap with actuator physics, mechanical backlash emulation, and a strict 61-D observation contract.

61-D observation contract

[ Proprioception: 48D ]
  0..3:   Base angular velocity from IMU gyro (rad/s)
  3..6:   Projected gravity vector in trunk frame (unit vector)
  6..20:  Joint positions relative to HOME_FRAME through backlash (rad)
  20..34: Joint velocities through backlash (rad/s)
  34..48: Last applied action (14D)

[ Commands: 13D ]
  48..51: Twist command [vx, vy, vyaw] (m/s, m/s, rad/s)
  51..55: Head pose delta [neck_pitch, head_pitch, head_yaw, head_roll] (rad)
  55..61: Body pose delta [x, y, z, roll, pitch, yaw] (m, m, m, rad, rad, rad)
Total: 48 + 13 = 61 dimensions

BAM M6 actuator modeling

Dynamixel XL330 servos exhibit non-linear behavior under load:

  • Battery voltage sag: Battery voltage drops from 8.2 V down to ~6.5 V under surge currents, reducing available torque: V_batt = max(V_min, V_oc - I_total * R_internal).
  • Back-EMF velocity limit: Torque decreases as motor velocity rises: V_eff = max(0, V_batt - Ke * |vel|).
  • Gearbox friction: XL330 gear trains introduce Coulomb friction and stiction thresholds that prevent motion under sub-threshold torques.
  • Transport delay: Models digital bus communication delay (1 to 4 steps) before commands reach the motors.

Mechanical backlash twin

To emulate 3D-printed horn play and gear backlash, microduck_walk_backlash.xml pairs every actuated joint with an unactuated passive_<joint>_backlash hinge in series (+/-1 degree free play). The simulation passes output-side encoder readings q_enc = q_servo + q_backlash into the 61-D observation vector, forcing policies to stabilize across mechanical deadbands.

Local PPO training run

Run a local PyTorch PPO training run on CPU or CUDA with push disturbance curriculum and terminal fall penalties:

# Anti-fall training with push disturbance curriculum
python -m microduck_brain.sim.train_smoke --iterations 5 --num-envs 4 --steps-per-env 64 --anti-fall

# Export trained policy weights directly to ONNX
python -m microduck_brain.sim.train_smoke --iterations 10 --export-onnx models/microduck_walk.onnx

Anti-fall training and balance recovery

To eliminate falls during bipedal locomotion, the simulation applies:

  • Terminal fall penalty: Tipping over (> 38.7 deg tilt, < 0.080 m trunk height) or non-foot ground strikes incurs an immediate -50.0 penalty.
  • Upright survival bonus: Continuous +2.0 reward per step while upright.
  • Non-foot collision gating: Inspects contact pairs; contact between floor and trunk, head, neck, or knees triggers instant termination.
  • Push disturbance curriculum: Periodic horizontal impulse kicks (0.15 to 0.25 m/s) applied to the trunk teach active recovery stepping.
  • Proactive velocity attenuation: In DuckBrain, compute_safe_velocity throttles forward speed to zero as body tilt approaches 15 degrees, preventing pitching falls before balance is lost.

End-to-end DuckBrain MuJoCo simulation

Execute high-level Behavior Tree goals (FETCH_BALL -> Search in-place turn -> Approach forward walk -> Pickup ground dip) driving the 50 Hz physics loop:

# Headless run with cycle latency and battery sag summary
python scripts/run_mujoco_sim.py --steps 250 --onnx models/microduck_walk.onnx --headless

# Interactive viewer mode (requires display)
python scripts/run_mujoco_sim.py --steps 250 --onnx models/microduck_walk.onnx --render

Real-task evaluation suite

The evaluation suite executes five multi-tier benchmark missions verifying speech intent parsing, reactive behavior tree transitions, dynamic push disturbance rejection, bus brownout interlocks, and balance-subordinated body language:

python scripts/run_brain_eval_suite.py

Benchmark results:

  1. fetch_with_push_rejection: Full multi-phase mission (Search -> Approach -> Pickup -> Complete). During active walking at step 50, a +0.25 m/s lateral impulse is injected into the trunk. The robot stabilizes with maximum tilt 4.9 deg, maintains trunk height > 0.117 m, completes ground pick, and emits sound feedback with 0 falls.
  2. battery_brownout_interlock: Tests Dynamixel bus voltage sag under high-torque acceleration. WorldState detects sag at 6.30 V (< 6.50 V low cutoff), engages brownout lock, holds lock across partial recovery at 6.65 V via Schmitt trigger hysteresis, and clears lock only when voltage reaches 7.15 V (> 6.80 V high threshold).
  3. fallen_state_safety_abort: Enforces non-foot ground collision detection. When trunk drops below 0.080 m, safety watchdog detects non-foot ground contact, terminates the episode with -50.0 penalty, and commands immediate motor limp mode.
  4. ambient_expression_balance_gating: Verifies that ambient head scans flow during high stability, but clamp instantly to 0.0 deg offset when stability drops, preventing gestures from destabilizing gait. Failure branch triggers inquisitive head tilt on first search failure, and resigned head shake on third consecutive failure.
  5. empirical_stability_envelope: Rigorously benchmarks physical recovery limits across lateral and sagittal impulses:
    • Lateral recovery envelope: vy <= 0.45 m/s (maximum tilt <= 8.4 deg, 0 falls).
    • Sagittal recovery envelope: vx <= 0.18 m/s (maximum tilt <= 10.9 deg, 0 falls; physically bounded by 1.35 cm foot contact patch).
    • Boundary overshoot trip: vy = 0.75 m/s trips tilt threshold, executing watchdog abort and preventing uncontrolled motor thrashing.

Isaac Lab policy export

Export trained checkpoints to standalone ONNX:

python isaac_lab/export_onnx.py --checkpoint logs/model.pt --output microduck_locomotion.onnx

Physical Microduck robot deployment

DuckBrain connects directly to Pollen Robotics physical Microduck biped robot over Unix domain sockets (/run/robotd.sock, /run/tofd/tof.sock) or across a TCP network tunnel.

Pre-flight hardware checks

Before running untethered, run the pre-flight verification script to test daemon connectivity, battery voltage (> 6.5V brownout limit), safety state, and sensor feeds:

# On physical robot (or over SSH tunnel):
python scripts/check_physical_duck.py

# Offline verification / CI dry-run:
python scripts/check_physical_duck.py --dry-run

Interactive brain execution

Launch the 20 Hz executive brain with an interactive natural-language console:

# Onboard CM4:
python scripts/run_physical_microduck.py --interactive

# Remote workstation over Wi-Fi (SSH forwarded sockets):
ssh -N -L 8088:/run/robotd.sock -L 8089:/run/tofd/tof.sock duck@microduck.local &
python scripts/run_physical_microduck.py --endpoint localhost:8088 --tof-endpoint localhost:8089 --interactive

Type commands at the prompt:

ducky> come
ducky> fetch ball
ducky> sit
ducky> quack
ducky> status
ducky> stop

For full systemd setup, brownout thresholds, and real-time core isolation details, see docs/physical_robot_setup.md.

License

Apache-2.0

About

Four-tier autonomous brain for the Pollen Robotics Microduck / Open Duck Mini 14-DOF biped: stateless intent parser, hysteresis world state, reactive behavior tree, MuJoCo sim-to-real, and real-time ONNX motor daemon.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages