Compilation & Mapping
Performance depends on FLOPs, infrastructure & hardware.
1. Compilation
An ML compiler lowers from Frontend API -> Dataflow Construction -> Intermediate Representation -> Graph / Tensor Optimization -> Kernel Execution.
1.1 Frontend API
For example, tensorflow (build then execute or declaritive, can optimize and good for distributed exec) or pytorch (build-and-execute or imperative, easy to debug).
1.2 Dataflow Construction
Makes data dependencies explicit to facilitate optimizations. Represent as a DAG.
For example, for forward DAG
: The corresponding backward DAG is:
1.3 Intermediate Representation
Bridge between high level models and low level execution using:
- Abstraction - removing unecessary details
- Layered Representations - i.e. MLIR
- Lowering pathway - converting from one representation to another
1.4 Graph / Tensor Optimization
1.4.1 Operator Fusion
Combines adjacent ops into a single fused op to reduce overhead. For example, nn.Sequential(nn.Linear(4, 4), nn.ReLU()) can be fused into a single kernel. Reduces kernel launches, better memory access.
1.4.2 Constant Folding
Folds constant subexpression at compile time.
1.4.3 Tiling
Divides large computations (e.g. matmul) into smaller tiles that fit in memory / cache. This improves data locality, enables parallel execution and reuses cache.
However, it requires extra memory to cache intermediate results. This optimisation strongly depends on the hardware (e.g. cache size, memory heirarchy, bandwidth, etc).
It must also handle irregular shapes or incomplete tile.
1.5 Kernel Execution
Finally, the optimized graph is lowered to either vendor-optimized libraries with precompiled kernels (e.g. cuBLAS, cuDNN, etc). This gives high performance with minimal codegen overhead.
Alternatively, custom kernel generation (e.g. CUDA, Triton, C++) enables kernel fusion, layout tuning, tiling, etc, but the code gen is more complex.
2. Hardware Basics
There is a cost-design tradeoff between performance, power usage and area (physical footprint, scalability), called PPA.
Moore's Law says the number of transistors on a chip doubles every 18 months. This is slowing down, so we need to optimize for energy efficiency.
Ahmdahl's Law says the speedup of a program using multiple processors is limited by the sequential fraction of the program. For example, if 10% of a program is sequential, the maximum speedup is 10x.
Memory Wall is the growing gap between CPU speed and memory speed. Cache (SRAM) is fast but small, DRAM is large but slow. This is why we need to optimize for data locality.