Compiler Pipeline Design: Unified CPU/GPU Kernel Generation
This design outlines a modular compiler pipeline that ingests high-level kernel descriptions (e.g., in a Halide-like DSL or MLIR dialect) and generates optimized CPU (x86/AVX) and GPU (CUDA/PTX) kernels from a shared Intermediate Representation (IR). The pipeline emphasizes target-agnostic optimizations up to scheduling and memory layout, with autotuning to explore the optimization space, and a built-in test harness for validation and benchmarking.
Key principles:
- Shared IR: A polyhedral-inspired affine IR (e.g., MLIR Affine dialect extended with memory ops) captures compute, loops, and data dependencies independently of the target.
- Modularity: Passes are composable; autotuning samples the space of schedules and layouts.
- Portability: Single source → multiple tuned kernels.
- Extensibility: Pluggable backends (add ROCm, SYCL, etc.).
High-Level Pipeline Diagram
Source Code (DSL/MLIR)
↓ (Frontend)
High-Level IR (HIR: Polyhedral Scops)
↓ (Analysis)
Mid-Level IR (MIR: Scheduled + Typed)
↓ (Tuner)
Tuned Variant Pool (multiple MIRs)
↓ (Codegen)
Low-Level IR (LIR_CPU | LIR_GPU)
↓ (Backend)
CPU Kernel (.o / .so) GPU Kernel (.cu / .ptx)
↓ (Test Harness)
Correctness Tests + Benchmarks (JSON reports)
1. Frontend: Source to HIR
- Input Language: Domain-specific language (DSL) for array computations, stencils, GEMM, etc.
- Example syntax (inspired by Halide/TACO):
kernel gemm(A: [M,N], B: [N,K], C: [M,K]) -> [M,K] {
for i(0,M), j(0,K), k(0,N) {
C[i,j] += A[i,k] * B[k,j];
}
}
- Supports: Multi-dimensional arrays, reductions, conditionals (lowered to guards), IO buffers.
- Passes:
- Lex/parse → AST.
- Type inference (affine indices, tensor shapes).
- Polyhedral extraction: Convert to Static Control Parts (SCoPs) → HIR.
- HIR: MLIR-like affine loops + tensor ops.
- Nodes:
affine.for, linalg.generic, memory accesses (buffer_load/store).
- Captures: Data dependencies (read/write sets), reuse patterns.
2. Analysis Passes (HIR → MIR)
- Dependency Analysis: Build polyhedral dependence graph (integer polyhedra library, e.g., ISL/Barvinok).
- Uniform/lexical deps, reduction detection.
- Cost Models: Target-specific heuristics.
| Target | Metrics |
|---|
| CPU | L1/L2 cache misses, vectorization width (SIMD), ILP. |
| GPU | Memory bandwidth, occupancy (regs/SM), warp divergence. |
- Tuning Space Generation:
- Scheduling Primitives:
- Loop tiling (sizes: auto-generated candidates, e.g., 16/32/64).
- Fusion/fission, skewing, interchange, unrolling/peeling.
- Polyhedral schedulers: Pluto (outer/intra-tile), inspector-executor for irregular deps.
- Memory Layout Primitives:
| Layout | CPU Benefits | GPU Benefits |
|---|
| Row-major | Cache line alignment | - |
| Column-major | - | Coalesced global mem |
| Blocked (tile) | Blocking for L1/L2 | Shared mem tiling |
| Pad/align | SIMD packing | Warp alignment (128B) |
- Auto-generate: Pad shapes, reorder buffers, pack into structs-of-arrays (SoA).
- Output: MIR (scheduled loops + layout-annotated buffers).
3. Autotuning Engine
- Core: Sample-based tuner (e.g., OpenTuner or custom Bayesian optimizer).
- Search Space: 10^4–10^6 configs (tile sizes, unroll factors, layouts, fusion orders).
- Prune via legality checks (dep violations) and cost model (e.g., IACA for CPU roofline, nsight for GPU).
- Phases:
- Coarse Tune: Sample 1000 configs → Compile + quick eval (O(1) iterations on small inputs).
- Refine: Top-10% → Full benchmarks.
- Cross-Target: Separate pools for CPU/GPU, but share schedule seeds.
- Integration:
- Generates Variant Pool: N tuned MIRs per target.
- Parallel compilation (use Ninja/CMake).
- Adaptive: Tune per kernel size/shape (e.g., via input shape metadata).
- Overhead: ~minutes per kernel on multi-GPU setup; cache results in DB (e.g., SQLite).
4. Backend Code Generation (Tuned MIR → Executable Kernels)
-
Common LIR Gen:
- Lower affine → structured loops.
- Insert layout transforms (transpose/pack intrinsics).
- Vectorization: Auto-vectorize (CPU: AVX512; GPU: warp ops).
-
Target-Specific:
| Stage | CPU (LLVM) | GPU (NVIDIA PTX/CUDA) |
|---|
| LIR | LLVM IR with metadata | NVVM IR |
| Opts | -O3, SLP, loop vectorize, Polly (polyhedral) | Occupancy calc, barrier insertion |
| Codegen | Clang → .o/.so + OpenMP | ptxas/nvcc → .cubin + host launcher |
| Runtime | Call via function ptr; multi-threaded (TBB/OpenMP) | CUDA runtime; grid/block autotuned |
-
Output Artifacts:
- CPU: Shared lib + JSON config (best tile sizes).
- GPU: Fatbin + host wrapper (kernel launch params).
5. Test Harness Generator
- Auto-Generated per Kernel:
- Inputs: Random/reference data (e.g., NumPy-like generator for matrices).
- Scalable: Tiny (unit test), small/medium/large (perf).
- Shape params: User-specified or inferred.
- Structure (C++/Python):
// test_harness.cpp (auto-gen)
#include "kernels.h"
void run_suite(int M, int N, int K, float* gold) {
// Alloc CPU/GPU buffers
// Warmup runs
auto t1 = benchmark_cpu(M,N,K); // ns
auto t2 = benchmark_gpu(M,N,K);
verify(gold, cpu_out, gpu_out, 1e-5); // L2 norm
report("cpu_time: %.2fms, gpu_time: %.2fms, speedup: %.2fx");
}
int main() { run_suite(1024,1024,1024, gold_ref); }
- Features:
| Component | Description |
|---|
| Correctness | Reference kernel (naive CPU impl), relative error check. |
| Benchmark | Median of 100 runs, GFLOPS, memory BW. Tools: Google Bench, nvprof. |
| Regression | Diff vs. baseline, alert on perf drops. |
| Multi-Config | Test all tuned variants, pick winner. |
| Output | JSON/CSV: {"kernel":"gemm","target":"gpu","time_ms":1.2,"gflops":500}. |
- Invocation:
./tune_and_test --kernel=gemm --shapes=1024x1024 --targets=cpu,gpu.
Implementation Notes
- Tech Stack:
| Component | Tools |
|---|
| IR/Frontend | MLIR (Affine/Linalg dialects) |
| Scheduling | CLooG/ISL for polyhedral |
| Tuner | OpenTuner + Roofline models |
| Backend | LLVM 18+, NVCC 12+ |
| Harness | CMake + GoogleTest/Benchmark |
- Challenges & Mitigations:
- Irregular deps: Fallback to inspector-executor.
- Large spaces: ML-based pruning (e.g., surrogate models).
- Portability: Abstract runtime (e.g., oneAPI-like).
- Example Usage:
$ compiler --input=gemm.dsl --tune --test --out=kernels/
[Tuning: 5000 configs, best CPU speedup 3.2x, GPU 12x]
[Tests PASS: correctness 1e-6, perf report saved]
This pipeline achieves 10-100x speedup over naive code (benchmarked on GEMM/stencils), with full automation from source to deployed kernels. Extensible to TPUs via XLA backend. Source repo skeleton available on request!