Inferensys

Glossary

Memory Hierarchy Optimization

Memory hierarchy optimization is the process of structuring computations and data layouts to maximize reuse of data in fast on-chip memory (caches, registers) and minimize costly accesses to slower off-chip memory (DRAM).
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
HARDWARE-AWARE MODEL DESIGN

What is Memory Hierarchy Optimization?

Memory hierarchy optimization is a core discipline in hardware-aware model design, focusing on structuring computations and data layouts to maximize data reuse in fast, on-chip memory and minimize costly accesses to slower, off-chip memory.

Memory hierarchy optimization is the systematic process of structuring neural network computations and data layouts to maximize the reuse of data in fast, on-chip memory (caches, registers) and minimize costly accesses to slower, off-chip memory (DRAM). This is a fundamental hardware/software co-design principle for efficient on-device inference, directly targeting the von Neumann bottleneck. The goal is to keep frequently accessed data—like weight tensors and intermediate activations—as close to the compute units as possible to reduce latency and power consumption.

Key techniques include operator fusion, which combines consecutive layers into single kernels to reduce intermediate data writes, and data layout transformations like NHWC to NCHW to align with hardware prefetchers. Engineers use the roofline model to analyze a kernel's operational intensity and identify if performance is bounded by memory bandwidth or compute. For small language models, this involves careful tiling of attention matrices and optimizing KV cache access patterns to fit within limited SRAM on edge NPUs and Tensor Cores.

MEMORY HIERARCHY

Key Optimization Techniques

Memory hierarchy optimization structures computations and data layouts to maximize reuse in fast, on-chip memory (caches, registers) and minimize costly accesses to slower, off-chip memory (DRAM).

01

Loop Tiling (Blocking)

Loop tiling is a fundamental code transformation that partitions large iteration spaces into smaller blocks (tiles) to fit the working set of data into a faster level of the memory hierarchy (e.g., L1/L2 cache). This exploits temporal locality by reusing data within a tile and spatial locality by accessing contiguous memory addresses.

  • Mechanism: A large matrix multiplication is broken into sub-matrix blocks. The tiles of matrices A and B are loaded into cache once and used for multiple computations.
  • Impact: Can reduce DRAM accesses by orders of magnitude, transforming memory-bound operations into compute-bound ones.
02

Data Layout Transformation

This technique reorganizes how data is stored in memory to align with the access patterns of the computation, minimizing cache misses and enabling efficient vectorized (SIMD) loads.

  • Key Strategies:
    • Structure of Arrays (SoA) to Array of Structures (AoS): Converting from AoS (struct {float x,y,z;}) to SoA (struct {float x[]; float y[]; float z[];}) enables contiguous, aligned loads of a single attribute across many data points, ideal for vectorized operations.
    • Memory Alignment: Ensuring data arrays start at addresses aligned to cache line boundaries (e.g., 64-byte) prevents split loads across lines.
  • Example: Computer vision pipelines often transform image data from interleaved channels (HWC) to planar format (CHW) for efficient convolutional filter application.
03

Kernel Fusion

Kernel fusion is a compiler optimization that merges multiple consecutive computational operations (kernels) into a single, compound kernel. This eliminates intermediate writes and reads of large tensors to and from DRAM, keeping data in registers or cache.

  • Classic Pattern: Fusing a convolution, batch normalization, and ReLU activation into one kernel. The output of the convolution is normalized and activated before being written back to memory.
  • Benefits:
    • Drastically reduces memory bandwidth pressure.
    • Increases arithmetic intensity (operations per byte fetched).
    • Reduces kernel launch overhead in frameworks like CUDA.
  • Tools: Compilers like TVM and XLA perform automatic kernel fusion during graph lowering.
04

Operator Reordering & Scheduling

This involves intelligently scheduling the execution order of operations in a computational graph to maximize data reuse and minimize peak memory footprint.

  • Principle: Schedule operations so that the output of one can be consumed immediately by the next while still in a fast cache, rather than spilling to DRAM.
  • Use Case: In a transformer block, carefully scheduling the order of attention heads and feed-forward network computations can keep key intermediate tensors resident.
  • Relation to Gradient Checkpointing: A trade-off technique where some activations are not saved during the forward pass to reduce memory, then recomputed during the backward pass. Optimal checkpointing selects which tensors to recompute to minimize total compute time under a memory budget.
05

Software-Managed Caches (Scratchpads)

Instead of relying solely on hardware-controlled caches, this technique uses scratchpad memory (SPM)—a small, fast, software-managed SRAM on-chip. The programmer or compiler explicitly controls data movement between DRAM and the scratchpad.

  • How it Works: Critical data blocks (e.g., a tile of a matrix) are DMAed into the SPM, processed completely, and results are written back. This provides predictable, low-latency access.
  • Hardware Context: Common in many NPUs, DSPs, and GPUs (e.g., CUDA shared memory, AMD local data share).
  • Advantage: Eliminates unpredictable cache thrashing and provides guaranteed bandwidth for real-time systems.
06

Sparsity-Aware Dataflow

Optimizes memory access and computation for neural networks with pruned weights (structured/unstructured sparsity) by skipping operations on zero values and using efficient storage formats.

  • Key Techniques:
    • Compressed Sparse Formats: Using CSR or CSC to store only non-zero values and their indices, dramatically reducing memory footprint and bandwidth needs.
    • Sparse Kernel Design: Specialized GPU/TPU kernels that load compressed data and use predicate masks to avoid multiplications with zeros.
    • Amortized Index Lookup: Grouping non-zero computations to reuse index loads.
  • Challenge: Exploiting fine-grained unstructured sparsity requires specialized hardware support (e.g., NVIDIA's Sparse Tensor Cores) to realize performance gains beyond just memory savings.
HARDWARE-AWARE MODEL DESIGN

How Memory Hierarchy Optimization Works

Memory hierarchy optimization is a core technique in hardware-aware model design that structures computations and data layouts to maximize data reuse in fast, on-chip memory and minimize costly accesses to slower, off-chip memory.

Memory hierarchy optimization is the systematic process of structuring neural network computations and data layouts to maximize the reuse of data in fast, on-chip memory (caches, registers) and minimize costly accesses to slower, off-chip memory (DRAM). This is governed by the locality of reference principle, which includes temporal locality (reusing data over time) and spatial locality (accessing adjacent data). The goal is to keep the working set of active tensors and weights within the limited but high-bandwidth SRAM caches of a GPU, NPU, or CPU, thereby avoiding the performance bottleneck of main memory bandwidth.

Key techniques include loop tiling (blocking), which partitions large matrix operations into smaller blocks that fit in cache, and operator fusion, where consecutive layers are combined into a single kernel to eliminate intermediate writes to global memory. For small language models and edge deployment, this involves designing efficient model architectures like those using depthwise separable convolutions and optimizing data formats to align with hardware features such as Tensor Cores or ARM NEON SIMD instructions. The roofline model is used to analyze if a kernel is compute-bound or memory-bound, guiding optimization efforts.

HARDWARE-AWARE DESIGN

Memory Hierarchy Levels & Characteristics

A comparison of the key attributes and performance characteristics across the primary levels of the memory hierarchy, from the fastest on-chip storage to the slowest off-chip memory, critical for hardware-aware model optimization.

Memory LevelTypical SizeAccess Latency (Cycles)BandwidthManaged ByPrimary Use in ML

Registers

~1-4 KB (per core)

1

1 TB/s

Compiler

Holding operands for active ALU/FPU/Tensor Core operations.

L1 Cache (Data)

32-128 KB (per core)

3-5

500 GB/s

Hardware

Staging data for the core's immediate computation; holds activations and weights for the innermost loops.

L2 Cache

256 KB - 4 MB (shared/core)

10-20

200-400 GB/s

Hardware

Larger working set for a core/compute unit; reduces access pressure on L1 and last-level cache.

L3 Cache / Shared L2 (Last-Level Cache)

4 - 128 MB (shared)

30-80

100-200 GB/s

Hardware

Shared data pool for multiple cores/processors; critical for model parallelism and batch processing.

High-Bandwidth Memory (HBM)

4 - 32 GB

~200

1-3 TB/s

Programmer / Runtime

On-package, high-bandwidth DRAM for accelerators (GPUs/NPUs); holds full model parameters and large batch data.

Dynamic RAM (DDR)

8 - 512 GB

~300

50-100 GB/s

Programmer / OS

Main system memory; holds datasets, model checkpoints, and working memory for CPU-based processes.

Solid-State Drive (NVMe)

512 GB - 10+ TB

~100,000

3-7 GB/s

OS / Filesystem

Persistent storage for training datasets, model archives, and swap space for out-of-core computation.

Hard Disk Drive / Network Storage

1+ TB

~10,000,000

< 1 GB/s

OS / Network

Cold storage for massive archives; accessed only during initial data loading or checkpointing.

MEMORY HIERARCHY OPTIMIZATION

Practical Examples in AI/ML

Memory hierarchy optimization is a critical engineering discipline that structures computations and data layouts to maximize data reuse in fast, on-chip memory (caches, registers) and minimize costly accesses to slower, off-chip memory (DRAM). The following examples illustrate its application across the AI/ML stack.

01

Loop Tiling (Blocking) for Convolutions

Loop tiling is a fundamental compiler optimization that restructures nested loops to operate on small blocks (tiles) of data that fit entirely within the CPU cache. This transforms a memory-bound operation into a compute-bound one.

  • Standard Convolution: Accesses large input and weight tensors from DRAM repeatedly, causing high latency.
  • Tiled Convolution: Partitions tensors into smaller tiles. A tile of input activations and corresponding weights are loaded into cache once and used for multiple computations, drastically reducing DRAM traffic.
  • Impact: Can improve inference throughput by 3-5x for convolutional layers by exploiting temporal and spatial locality.
02

Operator Fusion in Compilers (TVM, TensorRT)

Operator fusion is a graph-level optimization performed by compilers like Apache TVM and NVIDIA TensorRT. It merges multiple sequential layers (e.g., Convolution → BatchNorm → ReLU) into a single, fused kernel.

  • Mechanism: The compiler generates a custom kernel that performs the combined operations without writing intermediate tensors back to DRAM.
  • Benefit: Eliminates the read/write overhead for intermediate activations, reducing memory bandwidth pressure and kernel launch latency.
  • Example: Fusing a common ResNet block sequence can reduce memory accesses by ~40% and improve latency by 20-30% on GPU hardware.
03

Weight Stationary Dataflow in NPUs

Neural Processing Units (NPUs) employ specialized dataflow architectures that orchestrate data movement to keep the most frequently accessed parameters in on-chip buffers. Weight Stationary is a common strategy.

  • Process: The weights for a layer are loaded into a high-bandwidth SRAM buffer (weight buffer) once. The input activations are then streamed through the compute array, performing all necessary multiplications against the stationary weights.
  • Advantage: Minimizes power-hungry accesses to external DRAM for weights, which are typically reused across many input pixels or tokens.
  • Hardware Example: Google's TPU and many edge NPUs use systolic arrays with weight-stationary or output-stationary dataflows to achieve extreme energy efficiency (TOPS/W).
04

Gradient Checkpointing for Training

Gradient checkpointing is a memory-for-compute trade-off that enables the training of extremely deep models (e.g., 1000+ layers) on memory-constrained hardware.

  • Problem: Training requires storing all intermediate activations for the backward pass, leading to O(n) memory complexity with network depth.
  • Solution: Only a subset of activations (checkpoints) are stored during the forward pass. During the backward pass, missing activations are recomputed from the nearest checkpoint.
  • Result: Reduces memory consumption from O(n) to O(√n), allowing for 4-8x larger models on the same GPU memory at the cost of ~30% increased compute time for the recomputation.
05

Cache-Aware Attention in Transformers

Optimizing the Attention mechanism for cache hierarchy is crucial for efficient LLM inference. The key is to minimize data movement for the Key (K) and Value (V) caches during autoregressive decoding.

  • Standard Attention: For each new token, the entire K/V cache (growing with sequence length) is read from DRAM, creating a memory bandwidth bottleneck.
  • Optimized Attention:
    • Blocked Processing: Sequences are processed in blocks. K/V vectors for a block are prefetched into cache and reused for all queries in that block.
    • FlashAttention: A seminal algorithm that uses tiling to keep slices of Q, K, V in SRAM, performing the entire softmax and attention operation on-chip, reducing HBM accesses by orders of magnitude.
  • Impact: FlashAttention can achieve 2-4x speedup in training and reduce inference latency for long sequences.
06

Sparsity Encoding for Pruned Models

After pruning a model to induce sparsity (many zero weights), efficient inference requires encoding the sparse weight matrix to skip computations and minimize memory footprint.

  • Compressed Sparse Row (CSR): Stores only non-zero values and their column indices, plus row pointers. Enables efficient SpMM (Sparse Matrix-Matrix Multiplication) kernels.
  • Blocked Sparsity (e.g., 2:4): A structured pattern where 2 out of every 4 contiguous weights are non-zero. This pattern can be leveraged by hardware like NVIDIA Ampere GPUs with Sparse Tensor Cores, which skip zero blocks, effectively doubling theoretical throughput for matrix operations.
  • Memory/Compute Benefit: A model with 90% unstructured sparsity can reduce weight memory by 10x. With 2:4 structured sparsity, inference can see a 1.5-2x speedup on supported hardware.
MEMORY HIERARCHY OPTIMIZATION

Frequently Asked Questions

Memory hierarchy optimization is a critical discipline in hardware-aware model design, focusing on structuring computations and data layouts to maximize data reuse in fast, on-chip memory and minimize costly accesses to slower, off-chip memory. These techniques are foundational for achieving high performance and energy efficiency in modern AI systems, especially for edge deployment.

Memory hierarchy optimization is the systematic process of structuring neural network computations and data layouts to maximize the reuse of data in fast, on-chip memory (like caches and registers) and minimize costly accesses to slower, off-chip memory (like DRAM). This is a fundamental co-design principle for achieving high performance and energy efficiency, as data movement is often the primary bottleneck—not computation. The goal is to exploit temporal locality (reusing data recently accessed) and spatial locality (accessing data stored close together) to keep the working set of active tensors and weights within the fastest levels of the memory hierarchy during critical compute phases.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.