Co-Designing an NPU Instruction Set and Compiler Stack from Scratch

    This article explains how to co-design a neural processing unit (NPU) instruction set and its compiler stack from the ground up. It covers why instruction semantics and data-path constraints should be defined before operator lists, how to design instruction granularity, memory hierarchy, and synchronization semantics for compiler friendliness, how to build a verifiable compiler pipeline, and how to run full end-to-end large models. It also addresses training versus inference support, engineering artifacts, and the role of AI coding assistants in the workflow.

    Why Start from the Instruction Set Instead of an Operator List

    The value of a specialized neural processor (NPU) is often summarized as “making hot operators such as matrix multiplication, convolution, and normalization faster.” For engineering teams, however, a more robust starting point is to first define instruction semantics and data-path constraints, and then derive operator implementations. The reason is straightforward: operator lists change frequently as model architectures evolve, whereas once an instruction set is stable, the compiler, simulator, driver, and verification suites can evolve in parallel.

    The goal of hardware-software co-design can be expressed as three closed loops:

    • Hardware loop: Can instructions be executed deterministically within limited on-chip storage, bandwidth, and pipeline depth?
    • Compiler loop: Can high-level computation graphs be lowered to these instructions legally and efficiently, in a replayable and debuggable way?
    • System loop: Can runtime scheduling, memory management, and host-side interfaces support end-to-end models, rather than only single-operator microbenchmarks?

    If you accumulate operators first and add instructions afterward, the typical consequences are: every new fusion pattern changes the microarchitecture; the compiler fills with special cases; and simulation and pre-silicon verification diverge. Conversely, if you first specify clearly “what an instruction does, what it does not do, and how alignment and out-of-bounds accesses are handled,” subsequent extensions become more like filling in a table that has already been drawn.

    Instruction Set Design: Leave Interfaces for the Compiler, Not Slogans for Demos

    An NPU instruction set targeting large models need not pursue the orthogonal completeness of a general-purpose processor, but it must be internally consistent along the following dimensions.

    1. Granularity of Compute Primitives

    Hot spots in large-model inference are relatively concentrated: blocked matrix multiplication, elementwise nonlinearities, normalization, scaling and masking in attention, quantization/dequantization, and a small amount of control flow. There are two common choices for instruction granularity:

    • Fine-grained: Close to vector/tensor micro-operations. The compiler handles scheduling and fusion; hardware is simple, but instruction stream density and decode/issue pressure are high.
    • Coarse-grained: One instruction corresponds to a fused block of matrix-multiply-accumulate plus activation. Throughput looks good, but when the compiler cannot precisely match shapes and fusion patterns, performance degrades into a pile of “patch operators.”

    The more robust approach is layering: the lower layer provides composable tensor micro-instructions (load, multiply-accumulate, reduce, permute); the middle layer provides verifiable fusion templates (for example, “tiled GEMM + bias + activation”); the upper layer lets the compiler decide whether to instantiate a template. This avoids binding the hardware to any single model generation, and prevents the compiler from facing a black box that cannot be composed.

    2. Storage Hierarchy and Addressing Semantics

    NPU performance is almost always limited by data movement. The instruction set must explicitly answer:

    • Is on-chip buffer software-managed or hardware-cached? Software management favors deterministic latency but requires the compiler to perform precise lifetime analysis and double buffering.
    • Are addresses physical, partitioned, or tensor descriptors with stride/broadcast? Descriptors significantly shorten the instruction stream, but hardware decoding becomes more complex, and boundary checking must be nailed down in the specification.
    • Are quantization parameters, scaling factors, and masks passed as immediates, bypass registers, or tensor metadata? This directly affects instruction encoding width and context-switch cost.

    The specification should define “legal alignment, out-of-bounds behavior, and uninitialized reads” as simulatable contracts, rather than leaving them to each implementation’s “best effort.” Otherwise, the compiler optimizer and the hardware implementation will make different assumptions, and integration debugging costs grow exponentially.

    3. Control Flow and Synchronization

    Pure dataflow is friendly to static graphs, but large-model inference still has dynamic shapes, paging, and speculative decoding. The instruction set needs at least:

    • Lightweight synchronization (barriers, events, producer-consumer counters);
    • Predictable exceptions and traps (alignment errors, permissions, watchdog);
    • A consistency model with the host-side submission queue (when results become visible, when buffers can be reclaimed).

    It does not need a full OS-level interrupt system from day one, but the compiler and runtime must know “when a kernel ends and when its results become visible to the host.”

    The Compiler: Turning Graphs into Verifiable Instruction Streams

    “Hand-writing a new compiler” sounds like building a frontend from scratch, but the actual workload usually concentrates in the intermediate representation (IR) and backend legalization. A clear pipeline is:

    1. Import and normalization: Convert computation graphs into a unified IR, performing constant folding, operator normalization, and layout conventions (for example, unifying on a blocked row-major or tiling-friendly layout).
    2. Operator legalization: Lower frontend operators to hardware-supported primitives; for those that cannot map directly, either decompose them into primitive sequences or insert a software fallback path (fallbacks must be countable and disableable, otherwise performance numbers become misleading).
    3. Shape and tiling planning: Perform tiling according to on-chip buffer capacity, systolic array/dot-product unit width, and bandwidth. In large-model scenarios, attention and MLP tiling strategies differ and should be modeled with separate cost models rather than a shared heuristic.
    4. Fusion and scheduling: Fuse operators and overlap computation with data movement (double buffering) under legal dependencies. More fusion is not always better; it is constrained by register/buffer pressure and verifiability.
    5. Register/buffer allocation and instruction emission: Generate concrete instructions, insert synchronization, and complete address computation.
    6. Validation and replay: Compare numerically against an instruction-level simulator; save reproducible inputs, random seeds, and quantization configurations.

    The primary quality metric for the compiler should not be “peak utilization” but whether mapping failures are explainable. When a layer cannot fit into on-chip buffers or cannot satisfy alignment constraints, the diagnostic should indicate whether the cause is shape, layout, fusion, or synchronization. Otherwise, later attempts to “use AI-powered tools to assist backend generation” will also fall into uncontrolled patch loops.

    On using intelligent coding assistants: they are well suited to generating boilerplate (instruction encoding/decoding, test fixtures, simulator scaffolding), but they cannot replace the specification itself. Specifications, boundary conditions, and golden models must be human-reviewed and frozen; assistant-generated code should pass the same instruction-level tests, not merely “appear to run.”

    Runtime and End-to-End: From Single Operators to Full Large Models

    Instructions and the compiler only guarantee that “each layer computes correctly.” End-to-end execution additionally requires:

    • Memory planning: residency strategy for weights, activations, and KV cache; which stay resident on-chip and which use host memory or large-capacity device-side storage.
    • Quantization and precision policy: weight quantization, activation dynamic range, attention accumulation precision. These must be visible at compile time to avoid runtime silently escalating precision and exploding bandwidth.
    • Scheduling: multi-stream overlap, multi-core partitioning, and recompilation or shape specialization when sequence lengths change.
    • Correctness gates: in addition to final generated text, compare key tensors (for example, per-layer output statistics or logits of selected tokens); otherwise errors get masked in deep layers.

    “Running a large model” should be broken into staged gates: microbenchmarks (GEMM/normalization) → single transformer layer → small full network → decode loop at target scale. At each stage, freeze the meaning of performance counters (effective compute utilization, waiting on memory, synchronization idle), to avoid comparing numbers measured with different definitions later.

    Same Stack for Training or Inference Only?

    The original text mentions “then use this NPU to train models,” which requires separate evaluation. An inference-friendly instruction set emphasizes throughput, quantization, and deterministic scheduling. Training additionally requires:

    • Backward operators and high-bandwidth gradient write-back;
    • Mixed precision with hardware/compiler support for loss scaling;
    • Larger optimizer-state residency and update atomicity.

    The more pragmatic path is: in the first phase, make the inference stack reproducible and observable; add training instructions as an extension set, adding a backward mode on the same IR, rather than promising training peak performance on the first-version microarchitecture. If the goal is “using models to assist in generating a software-hardware full stack,” then specifications, tests, and simulation should be used as constraint inputs for generation, rather than rushing to automatically write out all the RTL first.

    Engineering Organization: Specification First, Generation Second

    A maintainable co-design effort should include at least the following documents and artifacts:

    • Instruction set manual (encoding, timing, exceptions, memory model);
    • Golden instruction-set simulator (with the same specification as the RTL);
    • Compiler legalization rules and cost model documentation;
    • Numerical and performance regression suites (including tiling boundaries, odd shapes, quantization overflow);
    • Host interface and driver submission/completion semantics.

    Intelligent programming tools can accelerate the simulator, assembler, and test generation, but changes must enter through specification diffs: first modify the contract, then modify the implementation, then extend the regression suite. Otherwise, “everything is generated” quickly becomes an unmaintainable situation where the entire stack drifts together with no way to localize problems.

    Summary

    The key to a deliverable NPU full stack is not showing how much code a single conversation produced, but making instruction semantics, compiler mapping, storage contracts, and end-to-end verification into one executable chain of specifications. First freeze “what instructions guarantee,” then let the compiler search for tiling and fusion within those constraints, and finally run large models with replayable simulation and layered gates. This gives you a stable backbone whether you later extend training instructions or use assistants to mass-generate boilerplate code.