J. Rogers, SE Ohio
In systems architecture terms, building a unified-memory pointer-passing framework that orchestrates three heterogeneous compute blocks without copying data is a massive deal—it is the exact architectural endgame behind runtimes like Apple's MLX and Modular's MAX Engine, built specifically for open-source ARM Linux.
On unified-memory heterogeneous ARM SoCs, replacing discrete-GPU memory abstractions and single-backend execution with an OS-level
On unified-memory heterogeneous ARM SoCs, replacing discrete-GPU memory abstractions and single-backend execution with an OS-level
dmabuf arena orchestrator—combining intra-layer CPU/GPU/NPU pipelining, explicit cache-coherency tracking, and safe-point checkpoint compaction—significantly improves tokens-per-second, time-to-first-token (TTFT), and performance-per-watt compared to existing runtimes (llama.cpp, ONNX Runtime, QNN).Part 1: Why the 3-Engine Orchestrator Model Matters
One Silicon Die, Three Separate Worlds
While the Snapdragon X Elite is a monolithic SoC (one physical silicon die) rather than separate physical chiplets, logically and electrically it behaves just like a multi-chiplet system:
- The Oryon CPU, Adreno X1-85 GPU, and Hexagon V73 NPU sit on separate clock domains, separate power islands, and separate memory-management units (SMMUs/IOMMUs) connected to a shared LPDDR5x memory fabric.
- Because each block has its own virtual address space and cache hierarchy, passing a raw userspace pointer (
0x7f8a...) from the CPU to the NPU fails immediately. Instead, the orchestrator passes a shared physical handle (dmabuf+ byte offset) that each engine maps once into its own local address space.
The Three Architectural Payoffs
- Breaking the Memory Wall: LLM inference is heavily memory-bandwidth bound. Every time a traditional framework copies a 4 GB tensor to a staging buffer, it wastes bandwidth and battery life moving bytes in circles. Zero-copy offset passing directs 100% of LPDDR5x bandwidth toward feeding the math units.
- True Pipeline Parallelism: An asynchronous orchestrator passes tiny 64-byte
TensorViewdescriptors (arena_id,byte_offset,shape,strides,sync_fence). While the Hexagon NPU crunches heavy prompt prefill chunks at 45 TOPS, the Adreno GPU can execute dynamic RoPE or FlashAttention, and the Oryon CPU can manage KV-cache paging and sampling—all mutating different offsets of the exact same physical memory slab. - Zero-Penalty Mid-Layer Fallback: NPUs are fast on static matrix math but rigid on custom activations; GPUs are flexible; CPUs have the lowest control-flow latency. If Layer 14 uses an unsupported op, the GPU or CPU runs that single op in-place on the buffer, and the NPU picks right back up on Layer 15 with zero serialization cost.
Part 2: First Steps — The Concrete Engineering Kickoff
Before writing neural network layers, start by building the Persistent Zero-Copy Arena and proving a 3-way hardware handshake in pure C23.
Step 1: Set Up Your Minimal Bare-Metal Toolchain
Install only the low-level Linux headers, Vulkan ICD loader, Mesa Turnip driver, and shader compiler—no high-level ML packages:
bash
sudo pacman -S base-devel linux-headers vulkan-headers vulkan-icd-loader vulkan-freedreno shaderc
Use code with caution.
(Verify permissions on
/dev/dri/renderD128, /dev/fastrpc-cdsp, and /dev/dma_heap/system so your user can open them directly without sudo.)Step 2: Define the Core
Arena and TensorView ABIDesign a single C header (
hal_memory.h) that represents one persistent physical slab mapped into all three address spaces at startup:c
typedef struct {
int dmabuf_fd; // From /dev/dma_heap/system
size_t total_size; // e.g., 4 GB persistent slab
void *cpu_base_ptr; // mmap() virtual address for Oryon CPU
VkDeviceMemory gpu_mem; // Imported via VK_KHR_external_memory_fd
VkBuffer gpu_buffer; // Bound once for Adreno Vulkan shaders
uint64_t npu_dsp_vaddr; // Mapped once via FASTRPC_IOCTL_MMAP
} ComputeArena;
typedef struct {
ComputeArena *arena;
size_t byte_offset; // Sub-allocation offset (64-byte aligned)
uint32_t shape[4];
uint32_t strides[4];
uint8_t dtype; // INT4, INT8, FP16, BF16, FP32
int acquire_fence_fd; // Linux sync_file FD to wait on before reading
int release_fence_fd; // Linux sync_file FD signaled when op finishes
} TensorView;
Use code with caution.
Step 3: Build the "3-Way Handshake" Proof of Concept (
hello_hetero.c)Write a single ~300-line C program that executes one continuous pipeline across all three engines with zero
memcpy calls:- Allocate: Open
/dev/dma_heap/systemand allocate a 16 MBdmabufslab viaDMA_HEAP_IOCTL_ALLOC. - CPU Write + Flush:
mmap()the buffer, populate an INT8 matrix on the Oryon CPU using<arm_neon.h>, and flush the CPU cache viaDMA_BUF_IOCTL_SYNC(DMA_BUF_SYNC_END | DMA_BUF_SYNC_WRITE). - GPU Transform: Import the exact same
dmabuf_fdinto Vulkan (renderD128), dispatch a minimal SPIR-V compute shader (vkCmdDispatch) that doubles every element in-place, and export a completion fence. - NPU Read: Map the exact same
dmabuf_fdto/dev/fastrpc-cdspviaFASTRPC_IOCTL_MMAP, trigger a lightweight CDSP RPC call, and verify the Hexagon DSP reads the GPU-modified values directly from RAM.
Part 3: Phased Project Plan (Solving the Three Hard Systems Problems)
Once the 3-way handshake works, the full framework build is structured into four phases—each explicitly engineered to solve one of the core pitfalls of heterogeneous shared memory.
Phase 1: The Persistent Arena Allocator & IOMMU Pinning
- The Engineering Problem to Solve: Virtual Address Translation & IOMMU Thrashing. Mapping and unmapping
dmabufhandles into the Adreno GPU and Hexagon NPU page tables on every inference step destroys latency. - Project Deliverables:
- Implement a Slab / Buddy Sub-Allocator on top of large, persistent
dma_heapallocations (e.g., allocating model-weight arenas and activation scratchpad arenas once at startup). - Enforce strict 64-byte and 128-byte cache-line alignment on all
byte_offsetsub-allocations so SIMD vector loads (vld1q_s8) and NPU HMX tiles never split across cache lines. - Implement static in-place buffer aliasing in the memory planner so intermediate activation offsets are reused across transformer layers without runtime allocations.
- Implement a Slab / Buddy Sub-Allocator on top of large, persistent
Phase 2: Explicit Cache Coherency & Hardware Fence DAG Scheduler
- The Engineering Problem to Solve: Cache Coherency (Silent Data Corruption) & Blocking Sync Overheads. The Oryon CPU maintains coherent L1/L2/L3 caches, whereas the Adreno GPU and Hexagon NPU often bypass CPU caches when reading LPDDR5x. Meanwhile, calling blocking
ioctl()waits after every op stalls the pipeline. - Project Deliverables:
- Build an Automatic Coherency Tracker inside the orchestrator: track the
last_writer_engine(CPU,GPU, orNPU) on everyTensorViewoffset. Only emitDMA_BUF_IOCTL_SYNCcache flush/invalidate calls when transitioning between the CPU and a non-coherent accelerator (skipping cache flushes entirely for GPU ↔ NPU handoffs). - Build an Asynchronous DAG Execution Queue backed by Linux
sync_filefile descriptors and Vulkan timeline semaphores (VK_KHR_timeline_semaphore). - Ensure Engine B begins executing at
byte_offsetthe microsecond Engine A's hardware fence signals—without waking a userspace CPU thread between ops.
- Build an Automatic Coherency Tracker inside the orchestrator: track the
Phase 3: Zero-Dependency Compute Backends (
cpu, gpu, npu)- The Engineering Problem to Solve: Hardware Specialization & Kernel Dispatch Latency. Each chip requires native kernels tuned to its exact silicon architecture.
- Project Deliverables:
backend_cpu(Oryon ARMv8.7-A): Write register-blocked C/Assembly micro-kernels usingSMMLA/UMMLA(i8mm) for quantized matrix multiplication,SDOT/UDOT(asimddp) for dot products, andVFMLA(fphp/bf16) for FP16/BF16, scheduled across a P-core pinned lock-free threadpool.backend_gpu(Adreno X1-85 Vulkan): Build a compact C Vulkan compute dispatcher (~800 lines) with pre-compiled SPIR-V pipelines for FlashAttention, RoPE, Softmax, RMSNorm, and SwiGLU/SiLU using wave-level subgroup reductions (subgroupAdd) and push-constant tensor shapes.backend_npu(Hexagon V73 FastRPC/QNN): Wrap/dev/fastrpc-cdspand Qualcomm’s QNN C API (QnnHtp.h) to compile/load static quantized subgraphs (INT8/INT4 linear projections and prefill blocks) into a persistent CDSP session reading straight fromnpu_dsp_vaddr.
Phase 4: Heterogeneous Router, Zero-Copy Model Loader & Public API
- The Engineering Problem to Solve: Workload Routing & Packaging as a Usable Framework. Turning raw systems primitives into a clean, portable runtime.
- Project Deliverables:
- Cost-Model Orchestrator Router: Automatically partition execution graphs—sending static, high-FLOP prefill matmuls to the NPU, dynamic attention/norm ops to the GPU, and token sampling/KV-cache updates to the CPU (with seamless mid-layer fallback if an op isn't supported on NPU).
- Zero-Copy Weight Loader: Parse GGUF and Safetensors files directly into
dma_heappages so weights move from NVMe SSD to NPU/GPU-accessible physical RAM without duplicate heap allocations. - Packaged Framework ABI: Expose a clean C23 header (
libx1e_ai.h) alongside lightweight Python (ctypes/cffi) and Rust FFI bindings, complete with a built-in profiler tracking per-engine utilization, fence wait times, and LPDDR5x bandwidth efficiency.
Note 1
When models are reduced to immutable, zero-copy
TensorView handles inside a shared dma_heap arena, you completely eliminate the brutal "load -> run -> tear down" lifecycle of traditional edge AI. Instead, your orchestrator manages physical LPDDR5x like a real-time database or video game engine:1. Resident Multi-Model Handles (Zero Cold-Start)
Because model weights are read-only and mapped once across CPU, GPU, and NPU address spaces, you can keep multiple specialized models resident simultaneously as lightweight C handles (
ModelHandle = a table of byte_offset + shape pointers):- A 0.5B routing/embedding model always pinned on the NPU (consuming almost zero idle power).
- A 3B–7B reasoning LLM sitting in the main arena ready to fire on the first token with 0 ms load time.
- A vision or Whisper audio encoder sharing the same physical slab.
- Bonus — Shared Weight Deduplication: If two fine-tuned models or LoRA adapters share a base backbone, both
ModelHandlestructs simply point to the exact samebyte_offsetbase weights in the arena, only allocating tiny extra offsets for their LoRA matrices.
2. Co-Resident Activations & Zero-Copy Handoffs Between Models
Because intermediate scratchpads and final output tensors live in the exact same arena as the model weights, chaining models together becomes a pointer handoff:
- Model A (e.g., an audio/vision encoder on the NPU) writes its final embedding tensor to
offset_out. - Instead of copying that embedding back to Python/CPU and re-uploading it, the orchestrator passes
offset_outdirectly asoffset_into Model B (an LLM on GPU/CPU). The output of one model is the input of the next.
3. Safe-Point Defragmentation & Checkpoint Compaction
As you dynamically load/unload LoRAs, grow KV-caches, or swap variable-length scratchpads across multiple resident models, physical memory fragmentation is the one real enemy of a long-running
dma_heap arena. Scheduling checkpoint defragmentation solves this cleanly without runtime stalls:- Why Safe Points Matter: You cannot move physical bytes while the Adreno GPU or Hexagon NPU has an active DMA transaction in flight.
- How Checkpoint Compaction Works:
- Quiesce at Chunk Boundaries: Between generation chunks, tool calls, or prefill-to-decode transitions, the orchestrator waits on all active
sync_filefences to drain (fence_wait_all()). - Slide & Patch Offsets: The allocator compacts fragmented holes by sliding relocatable allocations (like KV-cache pages or inactive model slabs) using fast SIMD
memcpy/ DMA blits, flushesDMA_BUF_IOCTL_SYNC, and atomically updates thebyte_offsetfields inside the affectedTensorViewhandles. - Zero Re-Mapping Overhead: Because the underlying
dmabuf_fdand its GPU/NPU IOMMU page tables never change—only thebyte_offsetinteger inside your userspace structs updates—compaction happens in microseconds without touching kernel page tables!
- Quiesce at Chunk Boundaries: Between generation chunks, tool calls, or prefill-to-decode transitions, the orchestrator waits on all active
How This Updates the Project Plan
This insight upgrades Phase 1 (Memory Manager) and Phase 4 (Orchestrator) with three concrete primitives:
ModelHandleRegistry: Read-only weight tables supporting base-weight pointer sharing (instant LoRA/adapter hot-swapping).- Two-Zone Arena Layout:
- Static/Pinned Zone (bottom of arena): Long-lived resident model weights.
- Dynamic/Compactable Zone (top of arena): Growing KV-caches, intermediate activations, and transient models.
arena_checkpoint_compact(): A deterministic safe-point API called between inference chunks that drains hardware fences, slides dynamic blocks to eliminate fragmentation, syncs CPU cache lines, and patchesTensorView.byte_offsetpointers in place.
Note 2: Zero-Copy Message-Passing Execution ("Data Sits in Place, Messages Flow")
Rather than hauling data and context into a monolithic inference pipeline, execution follows the DataObj / GrokThink dataflow paradigm: data sits stationary in the
ComputeArena, and lightweight messages flow between subscribed nodes.1. Binding Models to Stationary Data & Context
- Stationary Memory Handles: Model weights (
ModelHandle), live workspace context (persistent KV-caches, sensor ring-buffers, active state), and incoming prompts all reside at fixedbyte_offsetlocations inside thedma_heaparena, mapped once across Oryon CPU, Adreno GPU, and Hexagon NPU address spaces. - Zero-Copy Aliasing: Operations such as slicing, reshaping, splitting attention heads, or chaining one model's output into another's input require zero copies—nodes simply pass aliased
TensorViewhandles (arena_id,byte_offset,shape,strides,sync_filefence).
2. The Processing Task Binding Pattern
Executing an AI step requires no serialization, no ports, and no thread-blocking calls:
- Link Inputs: A processing task node (
TaskObj) subscribes to three stationary memory handles—the Model (ModelHandle), the Prompt (TensorView), and the Context (TensorView/ KV-cache offset). - Schedule & Dispatch: When any input property updates, a lightweight message queues the task on the orchestrator, dispatching the bound kernel directly onto the target silicon (Oryon, Adreno, or Hexagon) operating in-place on those exact physical offsets.
- Return Handle Message: Upon hardware fence completion, the task emits a result message containing only a new
TensorViewmemory handle pointing to the output slice in the arena—immediately triggering any downstream specialist micro-agents, verifiers, or UI nodes subscribed to that result.
Note 3: Fragmented Memory Arenas, Chip Affinity, and Asynchronous Pipeline Overlap
While unified-memory SoCs allow a single
dma_heap arena to be shared across all engines with zero copies, the TensorView handle architecture scales seamlessly to fragmented/discrete memory systems (such as a PC with system RAM and a small 2 GB discrete GPU) by introducing Arena Affinity:1. Memory Location Dictates Compute Affinity
- Arena-Bound Execution: Every
ComputeArenabelongs to a physical memory domain (ARENA_UNIFIED,ARENA_HOST_RAM, orARENA_DEVICE_VRAM). When aTensorViewhandle lives in a non-unified arena (e.g.,ARENA_DEVICE_VRAM), its weights and buffers are pinned directly to that chip's local memory bus—tying execution of those layers exclusively to that compute engine without PCIe round-trips. - Budget-Aware Layer Splitting: On constrained hardware (like a 2 GB GPU), the orchestrator fills the GPU arena with as many layers as fit (e.g., Layers 0–11) and places the overflow layers (Layers 12–23) into the CPU's system RAM arena.
- Explicit Bus Bridges Only at Domain Boundaries: Within the same arena, handoffs remain pure pointer/offset messages. Only when a message crosses between two distinct memory domains (
ARENA_DEVICE_VRAM→ARENA_HOST_RAM) does the orchestrator automatically schedule an asynchronous DMA transfer (vkCmdCopyBuffer/cudaMemcpyAsync) before signaling the downstream fence.
2. Asynchronous Pipeline Overlap (True Assembly-Line Execution)
Because
DataObj tasks are non-blocking and fence-driven, splitting a model across fragmented memory domains never leaves a chip sitting idle:- Concurrent Multi-Task Streaming: While the CPU finishes the tail layers (Layers 12–23) for Task A (Image 1) in system RAM, the GPU immediately pulls Task B (Image 2) into its 2 GB VRAM arena and starts computing Layers 0–11 simultaneously.
- Emergent Parallelism: By assigning each in-flight task its own ring-buffer
TensorViewoffset slot, every available silicon engine runs continuously at full throughput—turning even modest, fragmented hardware into an overlapping multi-stage assembly line.
Note 4: Deferred Memory Change Requests (RCU-Style Lease Draining)
To guarantee that no memory slice is ever mutated, moved, or unmapped while an active process or hardware engine is reading or writing it, the
ComputeArena enforces strict lease-counted immutability paired with deferred ChangeRequest scheduling:1. Per-Slice Lease Pinning (
active_leases)- Every sub-allocated region inside an arena maintains an atomic
active_leasescounter. - When a
TaskObjdispatches work on aTensorView(across Oryon CPU, Adreno GPU, or Hexagon NPU), it incrementsactive_leaseson its bound input/output slices and only decrements them inside the completion callback once itssync_fileor Vulkan fence signals. - Hard Invariant: No physical bytes or
byte_offsetmappings may be moved, compacted, or overwritten whileactive_leases > 0.
2. Non-Blocking
ChangeRequest Enqueue & Automatic Drain Execution- Schedule Without Stalling: When the orchestrator needs to compact fragmented scratchpads, evict a KV-cache, or perform an atomic firmware-style
ModelHandleswap, it attaches aChangeRequestcallback node to the target memory region and sets adrain_pendinggate so new tasks route to fresh/aliased slots. - Last-Out Triggers Execution: In-flight tasks finish completely uninterrupted. The exact completion callback that drops
active_leasesfrom1 -> 0detects the pendingChangeRequestand immediately queues it onto theDataObjscheduler. - Exclusive Ownership: Because
active_leases == 0and new readers are gated off, the deferred change request executes with guaranteed exclusive access—sliding bytes, flushingDMA_BUF_IOCTL_SYNC, patchingTensorView.byte_offsetpointers, and lifting the gate with zero locks and zero pipeline stalls.
No comments:
Post a Comment