ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

All Courses

Advanced Compiler and Runtime Optimizations for ML Workloads
Chapter 1: Foundation: ML Execution Stack and Challenges
The ML Model Deployment Gap
Overview of ML Compiler and Runtime Stacks
Performance Bottlenecks in ML Inference
Hardware for ML Acceleration
The Need for Specialized Optimizations
Chapter 2: Advanced Intermediate Representations for ML
Limitations of Traditional Compiler IRs
Principles of Multi-Level IRs
MLIR: Dialects and Operations
Representing High-Level ML Graphs (e.g., TF, TOSA)
Lowering Paths within MLIR
Extensibility and Custom Dialects
Hands-on Practical: Analyzing MLIR Representations
Chapter 3: Advanced Graph-Level Optimizations
Graph Rewriting Systems
Aggressive Operator Fusion Techniques
Memory-Aware Layout Transformations
Advanced Algebraic Simplification
Static Memory Planning and Allocation
Handling Control Flow in Graphs
Hands-on Practical: Implementing a Fusion Pass
Chapter 4: Tensor-Level Optimizations and Polyhedral Modeling
Representing Tensor Computations as Loop Nests
Introduction to Polyhedral Modeling
Iteration Domains, Access Functions, and Dependencies
Scheduling Transformations (Skewing, Tiling)
Code Generation from Polyhedral Schedules
Auto-Vectorization Techniques (SIMD)
Memory Hierarchy Optimization: Tiling and Prefetching
Hands-on Practical: Optimizing Loops with Polyhedral Tools
Chapter 5: Code Generation for Heterogeneous Hardware
Target-Specific Instruction Selection
Register Allocation for Vector/Matrix Units
GPU Code Generation: CUDA and ROCm Backends
Generating Code for Tensor Cores and Matrix Units
Targeting AI Accelerators (TPUs, NPUs)
Intermediate Formats for Heterogeneous Execution (SPIR-V)
Vendor-Specific Compiler Toolchains and Libraries (cuDNN, MIOpen)
Hands-on Practical: Analyzing Generated GPU Kernels
Chapter 6: Advanced Runtime Systems for ML
Runtime Architecture Overview
Handling Dynamic Shapes and Sizes
Efficient Memory Management Strategies
Asynchronous Execution and Scheduling
Scheduling for Heterogeneous Systems
Integrating Custom Operators and Kernels
Interoperability with ML Frameworks
Hands-on Practical: Implementing a Simple Allocator
Chapter 7: Just-In-Time (JIT) Compilation Techniques for ML
Motivation for JIT Compilation in ML
Tracing vs. Scripting Approaches
Intermediate Representation in JIT Systems
Runtime Specialization and Polymorphism
Profile-Guided Optimization (PGO) in JITs
Adaptive and Multi-Tier Compilation
Case Study: TensorFlow XLA
Case Study: PyTorch JIT (TorchScript)
Hands-on Practical: Analyzing JIT Compiled Code
Chapter 8: Quantization and Low-Precision Optimizations
Fundamentals of Model Quantization (INT8, FP8)
Representing Quantized Operations in IR
Compiler Passes for Quantization-Aware Training (QAT)
Post-Training Quantization (PTQ) Compilation Flows
Generating Low-Precision Kernels
Mixed-Precision Computation Optimization
Handling Quantization Scales and Zero Points
Hands-on Practical: Lowering Quantized Operations
Chapter 9: Profiling and Performance Analysis Tools
Challenges in Profiling Compiled ML Code
System-Level Profiling (CPU, GPU, Interconnect)
CPU Performance Analysis (VTune, perf)
GPU Kernel Profiling (Nsight Compute, ROCprof)
Correlating Framework Operations to Compiled Kernels
Memory Access Pattern Analysis
Interpreting Compiler Optimization Reports
Hands-on Practical: Profiling an Optimized Model

Graph Rewriting Systems

Optimizing the computation graph involves transforming its structure to enhance efficiency. These transformations, such as operator fusion or algebraic simplification, are not applied randomly. Instead, they rely on systematic mechanisms known as Graph Rewriting Systems. These systems provide the foundational framework for identifying specific patterns within the graph and applying predefined transformations to replace them with more optimal structures.

A graph rewriting system operates on the computation graph, typically represented as a Directed Acyclic Graph (DAG). In this DAG, nodes represent operations (like convolutions, matrix multiplications, or activations) and edges represent data dependencies, usually tensors flowing between operations.

Components of a Graph Rewriting System

A graph rewriting system primarily consists of two components:

  1. A set of Rewrite Rules: Each rule defines a specific transformation. It typically has two parts:

    • Pattern (or Left-Hand Side - LHS): Describes a subgraph structure to search for. This pattern specifies the types of operations, their connectivity (dependencies), and potentially constraints on node attributes (like data types or tensor shapes).
    • Replacement (or Right-Hand Side - RHS): Defines the new subgraph structure that should replace the matched pattern. This might involve creating new nodes, removing existing nodes, and adjusting the edges (data dependencies) to connect the replacement subgraph correctly into the main graph.
  2. An Engine: This component orchestrates the rewriting process. Its responsibilities include:

    • Pattern Matching: Efficiently searching the entire computation graph to find all occurrences of the patterns defined in the rewrite rules.
    • Rule Application: Selecting which matched rule to apply and performing the graph modification as specified by the rule's replacement pattern.
    • Strategy: Determining the order and iteration strategy for applying rules. Applying one rule might enable or disable other rules, so the strategy significantly impacts the final optimized graph.

Pattern Matching

Pattern matching is the process of finding subgraphs within the larger computation graph that are isomorphic (structurally equivalent) to the pattern defined in a rewrite rule. This process needs to examine:

  • Node Types: Matching the specific operations (e.g., Conv2D, ReLU, Add).
  • Connectivity: Ensuring the data dependencies between nodes in the subgraph match the pattern's specified edges.
  • Attributes and Constraints: Verifying that node attributes (like strides, padding, data types, or even constant values) satisfy any constraints specified in the pattern. For example, a fusion pattern might only apply if the data types match or if an operand is a constant.

Matching can range from simple checks for adjacent nodes to complex subgraph isomorphism problems. Techniques often draw from term rewriting and compiler optimization passes, sometimes employing specialized pattern description languages (like MLIR's Pattern Description Language - PDL) to formally define complex patterns and their associated constraints.

Replacement and Transformation

Once a pattern is matched, the rewriting engine applies the transformation defined by the rule's replacement part. This involves careful manipulation of the graph data structure:

  1. Node Creation: New nodes specified in the replacement pattern are instantiated.
  2. Node Deletion: Nodes that were part of the matched pattern but are not part of the replacement are removed.
  3. Edge Rewiring: Edges (data dependencies) are updated. Inputs to the original matched subgraph might be rerouted to inputs of the replacement subgraph. Outputs of the replacement subgraph are connected to the consumers of the original matched subgraph's outputs.

It is essential that the transformation maintains the semantic equivalence of the computation (or improves it, e.g., by removing redundant operations) and the overall validity of the graph structure.

Application Strategies

Since multiple rules might match different parts of the graph simultaneously, or applying one rule might create opportunities for others, the strategy for applying rules is important. Common strategies include:

  • Iterative Application: Repeatedly scanning the graph and applying rules until no more rules can be applied (reaching a fixed point).
  • Priority-Based Application: Assigning priorities to rules, ensuring that potentially more impactful or prerequisite transformations are applied first.
  • Cost Modeling: Using a cost model to estimate the performance impact (e.g., reduced execution time, memory usage) of applying a rule, guiding the selection process towards transformations likely to yield the most benefit.

Greedy application (applying the first matched rule) is often used for simplicity but doesn't guarantee finding the most optimal graph configuration, which is generally an NP-hard problem.

Example: Algebraic Simplification

For example, a simple algebraic identity: Transpose(Transpose(A)) = A. A rewrite rule can capture this:

  • Pattern: A Transpose operation whose input is the output of another Transpose operation.
  • Replacement: Replace the outer Transpose operation with a direct connection from the input of the inner Transpose to the consumers of the outer Transpose. Effectively, both Transpose nodes are bypassed and potentially removed if they have no other users.

The rewrite rule identifies two consecutive Transpose operations and replaces them with a direct connection from the original input to the final output.

Example: Simple Fusion

Another common pattern targets fusing an operation with its subsequent activation function, like Convolution -> ReLU.

  • Pattern: A ReLU operation whose input is the output of a Conv operation. Often includes constraints, e.g., the Conv output is only used by this ReLU.
  • Replacement: A single FusedConvReLU operation that takes the inputs of the original Conv and produces the output equivalent to the original ReLU. The original Conv and ReLU nodes are removed.

Fusing a Conv and ReLU operation into a single FusedConvReLU node reduces kernel launch overhead and improves data locality.

Graph rewriting systems provide the essential machinery for implementing the advanced graph-level optimizations discussed in the following sections. By defining patterns and their corresponding replacements, compilers can systematically restructure ML computation graphs for improved performance before exploring lower-level code generation. Understanding these systems is fundamental to appreciating how high-level optimizations like operator fusion, algebraic simplification, and layout transformation are realized in practice.

  • Graph Transformation: Basic Concepts and Applications, Hartmut Ehrig, Gregor Engels, Hans-Jörg Kreowski, Grzegorz Rozenberg (Editors), 2007 (Springer Berlin Heidelberg) DOI: 10.1007/3-540-27202-0 - A foundational textbook on graph transformation and rewriting systems, providing comprehensive theoretical concepts.
  • TVM: An Automatic End-to-End Optimizing Compiler for Deep Learning, Tianqi Chen, Thierry Moreau, Ziheng Jiang, Lianmin Zheng, Eddie Yan, Haichen Shen, Meghan Cowan, Leyuan Wang, Yuwei Hu, Luis Ceze, Carlos Guestrin, Arvind Krishnamurthy, 2018 13th USENIX Symposium on Operating Systems Design and Implementation (OSDI 18) (USENIX Association) - Presents TVM, a deep learning compiler that uses graph-level optimizations, including fusion and other transformations, enabled by a flexible rewriting system.
  • MLIR's Pattern Rewriting, The MLIR Team, Current - Official documentation detailing the pattern matching and rewriting mechanisms within the MLIR framework, including the use of Pattern Description Language (PDL).

© 2026 ApX Machine Learning