We are designing a compiler pipeline that can generate both CPU and GPU kernels from the same intermediate representation (IR). The pipeline should handle scheduling, memory layout, autotuning, and provide a test harness.
Steps:
IR Design: We need an IR that is sufficiently high-level to capture the parallelism and data movement, but also low enough to allow scheduling and memory layout decisions. It should be target-independent.
Frontend: Parses source code (e.g., in a Python-like DSL or C-like) and generates our IR.
Scheduling and Memory Layout: We need to separate the algorithmic description (what to compute) from the scheduling (how to compute, including parallelism, tiling, etc.) and memory layout (tensors in memory, data placement). The IR should allow annotations or transformations for these.
Target-Specific Lowering: From the IR with scheduling and memory layout, we generate either CPU or GPU code. This step will involve generating loops for CPU and thread/block hierarchies for GPU.
Autotuning: We need a way to search over different scheduling and memory layout options to find the best performing kernel for a given target. This could be integrated as a pass that explores the space of transformations and measures performance.
Code Generation: For each target, generate the actual code (C++ for CPU, CUDA/HIP/SYCL for GPU). We might use LLVM as a backend for CPU and a separate codegen for GPU.
Test Harness: Generate a test program that runs the kernel and verifies correctness (and maybe measures performance). The test harness should be able to run on both CPU and GPU.
However, note that generating both CPU and GPU kernels from the same IR is a complex task. We might look to existing projects like Tensor Comprehension, TVM, or ISL for inspiration.
Let's break down the pipeline:
Step 1: IR
We can use a representation similar to MLIR (Multi-Level Intermediate Representation) which is designed to be extensible and has multiple levels of abstraction.
Alternatively, we can design a simple IR that represents:
Parallelism annotations (e.g., which loops are parallel)
But note: we want to separate the algorithm from the schedule. So we might have:
An algorithmic IR that describes the computation without specifying the order (maybe using set operations or tensor expressions).
Then, we apply scheduling transformations (like tile, fuse, reorder, vectorize, etc.) to get a scheduled IR that is then lowered to target-specific loops.
Step 2: Scheduling
We need a scheduling language that can express:
Tiling: split a loop into nested loops (tiles).
Reordering: change the order of loops.
Parallelization: mark a loop as parallel (for CPU) or map to thread/block (for GPU).
Vectorization: for CPU, use SIMD instructions.
Unrolling: unroll loops.
Annotation of memory layout: which dimensions are contiguous, etc.
Step 3: Memory Layout
We need to represent the layout of tensors in memory (row-major, column-major, blocked, etc.) and possibly the placement of tensors (registers, shared memory, global memory for GPU; cache levels for CPU).
Step 4: Target-Specific Lowering
After scheduling and memory layout, we lower to:
For CPU: generate nested loops with OpenMP or SIMD intrinsics.
For GPU: generate CUDA/HIP kernels with thread and block indices.
Step 5: Autotuning
We can use a search algorithm (like random search, genetic algorithms, or reinforcement learning) to explore the space of schedules and memory layouts. We need a cost model to guide the search, or we can do empirical measurement.
Step 6: Code Generation
We can use LLVM for CPU code generation (if we lower to LLVM IR) and a separate code generator for GPU (or use LLVM to generate PTX for NVIDIA GPUs, but note that LLVM's PTX backend is not as mature as the CPU backends). Alternatively, we can generate CUDA C++ code and use nvcc.
Step 7: Test Harness
We generate a host program that:
Allocates and initializes input tensors.
Launches the kernel (either CPU or GPU) and copies data if necessary.
Verifies the result against a reference (maybe a simple sequential version).
Times the execution.
Proposed Pipeline:
Source Code (in a DSL)
|
v
Frontend -> Algorithmic IR (high-level tensor operations)
|
v
Scheduling Passes (transformations) -> Scheduled IR (with loops and parallelism)
|
v
Memory Layout Pass -> Scheduled IR with memory layout
|
v
Target-Specific Lowering (either CPU or GPU) -> Target IR (e.g., LLVM IR for CPU, or GPU IR)
|
v
Code Generation -> Object Code (or source code for GPU if we generate CUDA C++)
|
v
Linking and Test Harness Generation -> Executable
However, we want to generate both CPU and GPU from the same scheduled IR. So we don't commit to a target until the lowering step.
So:
Algorithmic IR -> [Scheduling and Memory Layout] -> Scheduled IR (target-independent)
Then, we have two paths:
code
CPU Lowering: Scheduled IR -> CPU Target IR (LLVM IR) -> CPU Code
GPU Lowering: Scheduled IR -> GPU Target IR (e.g., a representation that can be lowered to CUDA) -> GPU Code
Then, we generate a test harness that can run either.
But note: the test harness must be able to run on the host and dispatch to either CPU or GPU. So we might generate a host program that has both CPU and GPU versions and selects at runtime.
Alternatively, we generate two separate executables: one for CPU and one for GPU.
Considerations:
The IR must be expressive enough to capture both CPU and GPU schedules. For example, on GPU we might want to map loops to thread/block dimensions, but on CPU we map to vector widths and threads (OpenMP).
We might need to represent different mapping strategies. For example, on GPU we might have:
for tile in grid:
for thread in block:
compute element
But on CPU we might have:
for parallel region:
for vector in SIMD:
compute element
The memory layout might be different: on GPU we might want to use shared memory for tiles, on CPU we might want to use cache blocking.
The autotuning must consider both targets.
Implementation Plan:
Design the IR:
We can use a graph representation of tensor operations (like in TensorFlow or PyTorch) but then we need to convert to loops for scheduling.
Alternatively, we can start from a loop nest IR (like in polyhedral models) and then schedule.
Let's choose a polyhedral-inspired IR because it is good for scheduling and tiling.
Example:
code
Operation: C[i, j] = A[i, k] * B[k, j] for i in [0, M), j in [0, N), k in [0, K)
We can represent this as a set of constraints and an expression.
But note: we also want to support conditionals, reductions, etc.
We might use something like ISL (Integer Set Library) for representing iteration domains and schedules.
However, we want to keep it simple for the purpose of this design.
Alternatively, we can use an MLIR dialect for linalg (as in MLIR) which is a tensor-based IR that can be lowered to loops.
Steps:
code
- Use an MLIR-based design: we can define a "linalg" dialect that represents tensor operations (like matmul, conv) and then we apply transformations on that to get loops.
- Then we have a "scf" (structured control flow) or "memref" (memory references) dialect for loops and arrays.
- Then we target specific backends.
But note: MLIR already has a GPU lowering. We might reuse that.
However, the problem asks to design a compiler pipeline, so we can design our own simpler IR.
Let's design a simple IR for demonstration:
We have:
code
TensorType: shape and element type.
Operation:
- Compute: defines a tensor as an expression of other tensors.
- The expression can be a reduction or a pointwise operation.
Example:
%C = matmul %A, %B
where %A and %B are tensors.
But we also want to express loops explicitly? Maybe not at the beginning.
Alternatively, we can have:
code
Given the above, we can design the following:
Components:
IR:
We have:
code
Tensor: name, shape (list of dimensions)
Operation:
- name (e.g., "matmul")
- inputs: list of Tensors
- output: Tensor
- attributes: for matmul, we have the reduction dimension? Actually, the reduction dimension is the inner dimension of the first input and the outer dimension of the second input.
But we want to represent the loop nest. So we might have:
LoopNest:
- vars: list of variables (with names and ranges)
- body: a list of statements (assignments)
Assignment:
- lhs: TensorAccess (tensor, list of indices)
- rhs: Expression (which can be an operation, a tensor access, a reduction, etc.)
Reduction:
- reduce over a variable: sum, prod, etc.
We can have:
for i0 in 0..M:
for j0 in 0..N:
C[i0,j0] = 0;
for k0 in 0..K:
C[i0,j0] += A[i0,k0] * B[k0,j0]
This is a loop nest with an assignment that includes a reduction.
Alternatively, we can have:
C[i,j] = reduce(k, A[i,k]*B[k,j])
and then we schedule the reduction.
Given the time, we will use the loop nest representation.
So:
code
IR = LoopNest
But then we have multiple stages? For shared memory, we need to introduce new tensors (A_tile, B_tile) and their computations.
So we might have:
code
Function:
- inputs: [A, B]
- outputs: [C]
- stages: [Stage]
Stage:
- name
- vars: list of (var, range)
- computation: Expression (for each element of the stage's tensor)
- tensor: the tensor that this stage computes (with shape)
- memory_scope: (global, shared, local, etc.)
Then the schedule:
- We start with a default stage for C (with the full loop nest).
- Then we apply transformations that create new stages (for shared memory) and change the iteration domains.
This is a lot.
Implementation Plan:
Given the time, we will write a Python script that takes:
code
- M, N, K
- tile sizes (for GPU: BLOCK_I, BLOCK_J, BLOCK_K; for CPU: we might not need tile sizes? Actually, we use the same tiling for CPU? We can use the same tile sizes for CPU to have cache blocking.)
- target: cpu or gpu
and generates:
code
For CPU:
a C function:
void matmul_cpu(float* A, float* B, float* C, int M, int N, int K, int BLOCK_I, int BLOCK_J, int BLOCK_K) {
#pragma omp parallel for collapse(2)
for (int i0 = 0; i0 < M/BLOCK_I; i0++) {
for (int j0 = 0; j0 < N/BLOCK_J; j0++) {
for (int i1 = 0; i1 < BLOCK_I; i1++) {
for (int j1 = 0; j1 < BLOCK_J; j1++) {
float sum = 0.0;
for (int k0 = 0; k0 < K/BLOCK_K; k0++) {
for (int k1 = 0; k1 < BLOCK_K; k1++) {
sum += A[(i0*BLOCK_I+i1)*K + (k0*BLOCK_K+k1)] * B[(k0*BLOCK_K+k1)*N + (j0*BLOCK_J+j1)];
}
}
C[(i0*BLOCK_I+i1)*N + (j0*BLOCK_J+j1)] = sum;
}
}
}
}
}
But note: we have two outer loops (i0, j0) and we collapse them for OpenMP? Actually, we can collapse i0 and j0 to get a 2D parallel region.
However, the inner loops (i1, j1) are the tile inner loops, and then we have k0 and k1.
We might want to interchange the loops to have the vectorized loop innermost? But we are accumulating, so we cannot vectorize the accumulation easily.
We can vectorize the j1 loop? But j1 is the inner loop of the output and we are accumulating over k. We can try:
for i0 in ...:
for j0 in ...:
for i1 in ...:
for k0 in ...:
for k1 in ...:
for j1 in ...:
... # but then the access to C is not contiguous.
Given the time, we'll stick to the above.
For GPU:
a CUDA kernel:
__global__ void matmul_gpu(float* A, float* B, float* C, int M, int N, int K, int BLOCK_I, int BLOCK_J, int BLOCK_K) {
__shared__ float A_shared[BLOCK_I][BLOCK_K];
__shared__ float B_shared[BLOCK_K][BLOCK_J];
int i0 = blockIdx.x;
int j0 = blockIdx.y;
int i1 = threadIdx.y;
int j1 = threadIdx.x;
int i = i0 * BLOCK_I + i1;
int j = j0 * BLOCK_J + j1;
float sum = 0.0;
for (int k0 = 0; k0 < K/BLOCK_K; k0++) {
for (int k1 = 0; k1 < BLOCK_K; k1++) {
A_shared[i1][k1] = A[i*K + k0*BLOCK_K+k1];
B_shared[k1][j1] = B[(k0*BLOCK_K+k1)*N + j];
}
__syncthreads();
for (int k1 = 0; k1 < BLOCK_K; k1++) {
sum += A_shared[i1][k1] * B_shared[k1][j1];
}
__syncthreads();
}
if (i < M && j < N) {
C[i*N + j] = sum;
}
}
12. Autotuning:
code
13. Given the above, we can write a code generator that takes:
code
- operation: "matmul"
- shapes: M, K, N
- tile_sizes: BLOCK_I, BLOCK_J, BLOCK_K
- target: "cpu" or "gpu"
and generates the code.
We can also generate a test harness.
14. Autotuning:
code
We can write a Python script that:
- Defines a set of possible tile sizes (e.g., [16, 32, 64] for each dimension).
- For each combination, generate the GPU kernel, compile with nvcc, and run on a fixed input size to measure the time.
- Similarly for CPU, compile with gcc and OpenMP, and run.
Then select the best.
15. Limitations:
code
- Only supports matmul.
- For CPU, we are not using vectorization explicitly.
- For GPU, we assume the thread block is 2D and we use a fixed mapping.
- We assume row-major.
- We don't handle boundary conditions (if M, N, K are not multiples of tile sizes). We can add conditionals.
Given the time, we will ignore boundary conditions.
Implementation:
We'll write a Python script that generates the code.
Steps:
code
1. Define a function generate_code(operation, shapes, tile_sizes, target).
2. For matmul:
if target == 'cpu':
generate the CPU kernel with OpenMP.
if target == 'gpu':
generate the CUDA kernel with shared memory.
3. Generate the test harness.
4. Autotuning: try different tile_sizes and measure.
We'll assume the input shapes are M, K, N for A (M,K), B (K,N), C (M,N).
Let's code accordingly.
Note: the test harness will generate:
code
for CPU:
void matmul_cpu(...) { ... }
int main() {
// allocate and initialize A, B
// call matmul_cpu
// check result
}
for GPU:
__global__ void matmul_gpu(...) { ... }
int main() {
// allocate host A, B, C
// allocate device A, B, C
// copy A, B to device
// launch kernel
// copy C back
// check result
}
We'll generate the code as strings.
Given the complexity of the full design, we'll implement the simple version.
However, note that the assignment asks for a compiler pipeline that generates both CPU and GPU kernels from the same IR. We are not really using an IR, we are generating code based on parameters.
But we can consider the parameters (tile sizes, etc.) as the schedule, and the operation description as the IR.
We have:
code
IR: the operation (matmul) and the shapes.
Schedule: the tile sizes and the target.
Then we generate code.
This is a very simple pipeline.
But it doesn't have the flexibility to change the loop order arbitrarily.
Given the time, we'll go with this.
If we had more time, we would design a more general IR and schedule.
Let's code accordingly.
We'll write:
code
def generate_cpu_code(M, N, K, BLOCK_I, BLOCK_J, BLOCK_K):
code = f"""
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
void matmul_cpu(float* A, float* B, float* C, int M, int N, int K, int BLOCK_I, int BLOCK_J, int BLOCK_K) {{
#pragma omp parallel for collapse(2)
for (int i0 = 0; i0 < {M}/BLOCK_I; i0++) {{
for (int j0 = 0; j0 < {N}/BLOCK_J; j0++) {{
for (int i1 = 0; i1 < BLOCK_I; i1++) {{
for (int j1 = 0; j1 < BLOCK_J; j1++) {{
float sum = 0.0;
for (int k0 = 0; k0 < {K}/BLOCK_K; k0++) {{
for (int k1 = 0; k1 < BLOCK_K; k1++) {{
sum += A[(i0*BLOCK_I+i1)*{K} + (k0*BLOCK_K+k1)] * B[(k0*BLOCK_K+k1)*{N} + (j0*BLOCK_J+j1)];
}}
}}
C[(i0*BLOCK_I+i1)*{N} + (j0*BLOCK_J+j1)] = sum;
}}
}}
}}
}}
}}
int main() {{
int M = {M}, N = {N}, K = {K};
float *A = (float*)malloc(M * K * sizeof(float));
float *B = (float*)malloc(K * N * sizeof(float));
float *C = (float*)malloc(M * N * sizeof(float));
// initialize A and B with random values
for (int i = 0; i < M*K; i++) A[i] = (float)rand() / RAND_MAX;
for (int i = 0; i < K*N; i++) B[i] = (float)rand() / RAND_MAX;
// compute reference on CPU (naive)
float *C_ref = (float*)malloc(M * N * sizeof(float));
for (int i = 0; i < M; i++) {{
for (int j = 0; j < N; j++) {{
float sum = 0.0;
for (int k = 0; k < K; k++) {{
sum += A[i*K + k] * B[k*N + j];
}}
C_ref[i*N + j] = sum;
}}
}}
// call the tiled kernel
matmul_cpu(A, B, C, M, N, K, {BLOCK_I}, {BLOCK_J}, {BLOCK_K});
// check
for (int i = 0; i < M*N; i++) {{
if (fabs(C[i] - C_ref[i]) > 1e-5) {{
printf("Error at %d: %f vs %f}\\n", i, C[i], C_ref[i]);
return 1;
}}
}}
printf("CPU kernel passed.\\n");
free(A); free(B); free(C); free(C_ref);
return 0;
}}
"""
return code
Similarly for GPU.
But note: the GPU kernel uses shared memory and we have to handle the case when M, N, K are not multiples of the block sizes? We can add conditionals in the kernel.
We'll assume they are multiples for simplicity.
Now, the autotuning:
code
We can define a set of tile sizes:
tile_sizes = [16, 32, 64]
Then for each combination (bi, bj, bk) in product(tile_sizes, tile_sizes, tile_sizes):
generate the code for GPU, compile and run, and measure time.
We'll use the Python subprocess to compile and run.
However, we need to have CUDA installed for GPU.
We'll assume we are on a system with nvcc.
Steps for autotuning:
code
For each tile size:
Write the code to a file (e.g., matmul_gpu.cu)
Compile: nvcc -O3 -arch=sm_XX matmul_gpu.cu -o matmul_gpu
Run: ./matmul_gpu
Capture the time (we can measure inside the kernel or in the host code).
We'll modify the GPU kernel to include timing.
But note: we want to measure the kernel time only, so we can use cudaEvent_t.
Given the time, we might not implement the full autotuning, but we can outline it.
Given the assignment, we are to design the pipeline, not necessarily implement the entire thing.
So we can describe the design and then show a simple implementation for matmul.
Conclusion:
code
We have designed a simple compiler pipeline that:
- Takes an operation (matmul) and tile sizes.
- Generates CPU code (with OpenMP) and GPU code (with shared memory) from the same "IR" (which is just the operation and the tile sizes).
- Provides a test harness for both.
- Can autotune the tile sizes by generating code for each set and measuring the runtime.
This is a limited design but illustrates the concept.
For a more general design, we would need a more expressive IR and schedule.
Let's write the code for the CPU and GPU generators and the autotuning script.
We'll write:
code
generate_cpu(M, N, K, BLOCK_I, BLOCK_J, BLOCK_K)
generate_gpu(M, N, K, BLOCK_I, BLOCK_J, BLOCK_K)
Then a function autotune_gpu(M, N, K, tile_sizes) that tries all combinations and returns the best.
We'll also write a function autotune_cpu.
But note: for CPU, we might want to tune the OpenMP number of threads? We can set OMP_NUM_THREADS.
We can also tune the tile sizes for CPU.
We'll do:
code
For each (bi, bj, bk) in tile_sizes:
generate the CPU code, compile (without nvcc, just gcc), run, and measure.
However, we have to compile and run each time.
We can write a C program that takes the tile sizes as arguments and then runs the kernel, and then we call that from Python.
Alternatively, we can generate the code with the tile sizes embedded, compile, and run.
Given the time, we'll generate a separate executable for each tile size.
This is expensive, but for small matrices and a small set of tile sizes, it's acceptable.
Let's code accordingly.
We'll assume we are on Linux and have gcc and nvcc.
We'll write the Python script to:
code
1. Generate the code for a given set of tile sizes and target.
2. Write to a file.
3. Compile the file.
4. Run the executable and capture the time.
5. Return the time.
Then for autotuning, we iterate over the tile sizes and pick the minimum time.
We'll handle errors.
Let's code accordingly.
Note: We are generating C code for CPU and CUDA for GPU.
We'll generate:
code
For CPU: a .c file that includes the kernel and main.
For GPU: a .cu file.
Given the time, we'll assume sm_75 (for Turing) or adjust.
Let's code.
I'll design a comprehensive compiler pipeline that generates both CPU and GPU kernels from a unified intermediate representation (IR). This is inspired by systems like TVM, MLIR, and Triton but consolidated into a single coherent pipeline.
Compiler Pipeline Architecture
code
Source (Python DSL/C++)
↓
Frontend → Unified IR (target-agnostic)
↓
IR → Scheduling & Memory Layout Optimization
↓
[Target-Specific Lowering]
├── CPU Backend → LLVM IR → Machine Code
└── GPU Backend → GPU IR (SPIR-V/PTX) → CUDA/HIP/SYCL
↓
Code Generation & Packaging
↓
Test Harness & Autotuning Framework
1. Unified Intermediate Representation (IR)
IR Design Principles:
Separation of concerns: Algorithm vs. schedule vs. memory layout
Target-neutral: No CPU/GPU-specific constructs at this level
class DualTargetCompiler:
def __init__(self):
self.parser = FrontendParser()
self.ir_builder = IRBuilder()
self.scheduler = Scheduler()
self.cpu_backend = CPUBackend()
self.gpu_backend = GPUBackend()
self.autotuner = Autotuner()
self.test_gen = TestHarness()
def compile(self, source, target="both", tune=False):
# 1. Parse source → Unified IR
ir_module = self.parser.parse(source)
# 2. Apply default schedule
schedule = self.scheduler.default_schedule(ir_module)
# 3. Autotune if requested
if tune:
best_schedule = self.autotuner.tune(
ir_module,
target=target,
search_space=self.autotuner.default_space()
)
schedule = best_schedule
# 4. Lower to target(s)
artifacts = {}
if target in ["cpu", "both"]:
artifacts["cpu"] = self.cpu_backend.lower(schedule)
if target in ["gpu", "both"]:
artifacts["gpu"] = self.gpu_backend.lower(schedule)
# 5. Generate test harness
test_code = self.test_gen.generate(ir_module, target)
return {
"artifacts": artifacts,
"tests": test_code,
"schedule": schedule
}
def build_and_test(self, compile_result):
for target, code in compile_result["artifacts"].items():
# Compile
obj = self.compile_code(code, target)
# Link with test harness
exe = self.link(obj, compile_result["tests"], target)
# Run tests
result = self.run_tests(exe)
yield (target, result)
7. Example Usage
python
# User writes high-level code
@tvm.script
def matmul(A: tensor<MxKxf32>, B: tensor<KxNxf32>) -> tensor<MxNxf32>:
C = output_tensor((M, N))
for i in range(M):
for j in range(N):
for k in range(K):
C[i, j] += A[i, k] * B[k, j]
return C
# Compile for both targets with autotuning
compiler = DualTargetCompiler()
result = compiler.compile(
matmul,
target="both",
tune=True
)
# Run tests
for target, test_result in compiler.build_and_test(result):
print(f"{target} tests: {'PASS' if test_result.passed else 'FAIL'}")
print(f"Best schedule: {result['schedule'].config}")
print(f"Kernel time: {test_result.time}ms")
8. Advanced Features
Cross-Target Optimization:
CPU/GPU co-execution: Pipeline parallelism between CPU and GPU
Unified memory: Use unified virtual addressing when available
Dynamic dispatch: Runtime selection based on input size
The key innovation is single source of truth (the unified IR) with separate but derived code generation paths, allowing:
Single optimization description
Shared autotuning space
Consistent validation
Performance portability across architectures
This pipeline enables developers to write algorithms once and get optimized CPU/GPU implementations with automated performance tuning, while maintaining correctness through unified testing infrastructure.
Operation with iteration variables:
for i0 in 0..M {
for i1 in 0..N {
%C[i0, i1] = 0;
for i2 in 0..K {
%C[i0, i1] += %A[i0, i2] * %B[i2, i1];
}
}
}
This is the loop nest IR. Then we can apply transformations:
code
- Tile the i0 and i1 loops with tile sizes (s0, s1) to get:
for i0o in 0..M/s0 {
for i0i in 0..s0 {
for i1o in 0..N/s1 {
for i1i in 0..s1 {
%C[i0o*s0+i0i, i1o*s1+i1i] = 0;
for i2 in 0..K {
%C[...] += ...;
}
}
}
}
}
- Then we can parallelize the outer loops (i0o, i1o) for CPU, or map them to grid for GPU.
- Then we can vectorize the innermost loops for CPU, or map inner loops to threads for GPU.
So we need an IR that represents nested loops with an expression at the innermost level.
Let's define:
code
LoopNest:
- A list of loop iterators (with names and ranges)
- A body which is a statement (could be a sequence of statements)
Statement:
- Assignment: lhs = rhs
- where lhs is a tensor access (with indices that are linear combinations of loop variables)
- rhs is an expression (arithmetic, tensor accesses, reductions)
But note: the reduction in the inner loop is over i2. So we need to represent reductions.
Alternatively, we can represent the entire operation as a formula:
code
C[i, j] = sum_{k} A[i, k] * B[k, j]
and then the loop nest is the evaluation order.
So we might have two levels:
code
- High-level: tensor operations with reductions and indexing.
- Low-level: loop nests.
How to connect? We can start from the high-level and then lower to loops by iterating over the iteration space.
We can use the polyhedral model: the computation is a set of pieces (scatter/gather) and the schedule is a mapping from iteration space to time.
But for simplicity, let's stick to a loop nest IR that we can transform.
Scheduling and Memory Layout:
We need to represent:
code
- Tiling: split a loop into outer and inner loops.
- Reordering: change the order of loops.
- Parallelization: mark a loop as parallel (for CPU) or as a grid/block dimension (for GPU).
- Vectorization: for CPU, mark a loop as vectorized (with a factor).
- Unrolling: unroll a loop by a factor.
We also need memory layout:
code
- We can have a layout transformation that changes the order of dimensions in a tensor (like transposing) but that might be part of scheduling (by changing the index order in the tensor access).
- Alternatively, we can have a separate layout annotation for each tensor: which dimension is contiguous, the stride, etc.
But note: in the loop nest, the tensor access expressions use the loop variables. If we change the layout, we change the mapping from logical index to physical index.
So we might have:
code
Tensor layout: a permutation of dimensions and a padding/blocking structure.
However, for autotuning we want to explore different layouts. So we need to have a way to represent the layout as part of the schedule.
We can represent the layout as a transformation on the tensor access expressions.
Example:
code
Original: A[i, k] -> in memory row-major: offset = i * K + k.
If we block the first dimension by s0 and the second by s1, then:
Blocked: A[block_i, inner_i, block_k, inner_k] -> but we might flatten to 2D: [block_i * (K/s1) + block_k, inner_i * s1 + inner_k]?
This gets complicated.
Alternatively, we can have a separate pass that rewrites the tensor access based on a layout transformation.
We might decide to keep the logical indices in the computation and then have a separate mapping to physical indices.
So:
code
In the computation, we use logical indices (i, j, k).
Then, for each tensor, we have a layout function that maps logical indices to physical indices.
Example:
Physical index for A: (i, k) -> (i, k) for row-major.
If we want to tile the i and k dimensions, we might change the layout to:
(i, k) -> (floor(i/s0), floor(k/s1), i % s0, k % s1)
and then we might reorder the physical dimensions.
But then the memory access pattern changes.
We can represent the layout as a sequence of transformations (like split, reorder, fuse) on the tensor dimensions.
This is similar to the schedule for the loop nest, but for the tensor dimensions.
So we might have two kinds of transformations:
code
- Loop schedule: transforms the iteration space (the loops).
- Tensor layout: transforms the index space of each tensor.
And the computation uses logical indices. Then we apply the layout transformation to each tensor access to get the physical indices.
Then, we generate code that uses the physical indices to access memory.
This way, the computation remains the same, but the memory access pattern changes.
Example:
code
Original computation: C[i,j] = sum_k A[i,k] * B[k,j]
Layout for A: split i into (i0, i1) with factor s0, and split k into (k0, k1) with factor s1. Then reorder to (i0, k0, i1, k1). Then fuse (i0, k0) -> block0, and (i1, k1) -> thread0? Not exactly.
Actually, the layout transformation is independent of the loop schedule? Not really: the loop schedule might already split the loops and then we map the inner loops to threads. But the layout transformation might split the tensor dimensions to match the loop tiling.
Alternatively, we can think of the layout as the way we store the tensor in memory, and then the loop schedule determines how we access it.
We might have:
code
Loop schedule: defines the order of iteration and the tiling of the loop nest.
Tensor layout: defines the order of dimensions in memory (contiguous) and the blocking for cache/shared memory.
Then, when we generate the code, we use the loop variables to compute the physical indices according to the layout.
Example:
code
Loop nest: for i0 in 0..M/s0, for i1 in 0..s0, ...
Tensor A has layout: (i, k) -> (i, k) for row-major, but if we want to use shared memory for a tile of A, we might change the layout to block the i and k dimensions and then store the tile in shared memory in a transposed order?
This is getting too complex for a simple design.
Let's simplify:
code
We assume that the tensors are stored in row-major (or column-major) and we don't change the layout. Instead, we change the loop order to match the memory layout for better locality.
But then we cannot use shared memory in GPU? We need to copy to shared memory.
So for GPU, we might have:
code
- The original tensor is in global memory (with a given layout, say row-major).
- We want to load a tile into shared memory. Then we need to change the layout of the tile in shared memory (maybe to bank-friendly or to match the thread access pattern).
Therefore, we need to represent multiple buffers (the original global buffer and the shared memory buffer) and transformations between them.
We might need to represent tensor views with different layouts.
Given the complexity, perhaps we should limit the scope:
code
- For CPU: we assume row-major and we rely on cache blocking by tiling the loops and then the innermost loop accesses contiguous elements.
- For GPU: we assume row-major in global memory, and we copy tiles to shared memory. The shared memory layout might be the same as global or transposed to avoid bank conflicts.
But then we need to handle the copy from global to shared memory.
So the IR must be able to express:
code
- Multiple buffers (tensors) with possibly different layouts.
- Copy operations between buffers.
This is getting too heavy.
Alternatively, we can have:
code
- The algorithm is defined on logical tensors (with logical indices).
- We have a set of buffers (physical memory) and a mapping from logical tensors to buffers (with a layout transformation).
Then, the loop nest is over the logical indices, but when we access a tensor, we use the layout transformation to get the physical index in the buffer.
And then we can have separate buffers for global and shared memory in GPU.
Example:
code
We have a logical tensor A_logical (with index i,k).
We have a buffer A_global with row-major layout: index (i,k) -> i*K + k.
We have a buffer A_shared with blocked layout: index (i,k) -> (i % s0) * (K % s1) + (k % s1) [but note: we tile by s0 and s1, and then we might have multiple tiles].
This is complex.
Given the time, let's simplify further:
code
We will focus on the loop schedule and assume that the tensors are stored in a fixed layout (row-major). Then, for GPU, we will generate code that uses shared memory by explicitly copying tiles.
But then the copying must be part of the schedule.
So we might have:
code
Schedule includes:
- Loop splitting (tiling)
- Mapping loops to parallel regions (for CPU) or to thread/block (for GPU)
- Vectorization (for CPU)
- And for GPU: we might have a separate "copy to shared memory" operation that is scheduled.
We can represent the copy as a separate operation that reads from global and writes to shared, and then the compute kernel reads from shared.
Then the schedule must include the copy and the compute.
So the IR must be able to represent multiple kernel-like functions? Or we can have one kernel that does both copy and compute? Usually, we separate the copy and compute in GPU.
We might have:
code
Kernel1: copy tile from global to shared.
Kernel2: compute using shared memory.
But then the schedule must coordinate the two.
Alternatively, we can have a single kernel that does:
code
for each tile in the grid:
copy tile from global to shared (by the entire thread block)
synchronize
compute using shared memory
So we need to represent:
code
- Thread block collaboration: shared memory and synchronization.
This is very GPU-specific.
Given the complexity, we might decide that our IR is for a single kernel that operates on logical tensors, and then we rely on the target lowering to insert shared memory copies and synchronization.
But then the target lowering for GPU must know how to tile and when to copy to shared memory.
Alternatively, we can have the schedule specify:
code
- Which loops are for copying and which for computing.
- And which buffers are in shared memory.
We might need to represent:
code
Buffer allocation: for each tensor, we have multiple buffers (global, shared) and a mapping.
This is too much.
Given the constraints, let's design a simpler pipeline that only does CPU and GPU without shared memory for GPU, and without explicit layout transformations (assume row-major). Then we can extend later.
But then we lose the main benefit of GPU (shared memory).
Alternatively, we can assume that the user will write the GPU kernel with shared memory explicitly, and we only generate the compute kernel? That defeats the purpose.
Let's look at existing solutions:
code
TVM: uses a scheduling language that can specify:
- Tiling (split)
- Vectorization (vectorize)
- Parallelization (parallel)
- For GPU: bind loops to thread/block (thread_binding) and use shared memory (cache_read, cache_write).
So TVM has:
- s = te.create_schedule(C.op)
- x, y = s[C].split(s[C].op.axis[0], factors)
- s[C].parallel(x)
- s[C].vectorize(y)
- For GPU: s[C].bind(x, thread_binding)
And for shared memory:
- s[shared].compute_at(s[C], x) # where shared is the stage that computes the shared memory tile.
So TVM has the concept of stages (intermediate tensors) and you can compute one stage at the granularity of another stage.
So we need to represent:
code
- A computation graph with intermediate tensors (stages).
Then, the schedule can insert new stages (for shared memory) and compute them at certain points.
This is getting very complex.
Given the time, let's simplify:
code
We will design for:
- A single operation (like matmul) that takes two input tensors and produces one output tensor.
- The schedule will be:
- Tiling the two output dimensions (i and j) and the reduction dimension (k).
- For CPU: parallelize the outer tiled loops, vectorize the inner loops.
- For GPU: bind the outer tiled loops to grid and the inner tiled loops to block, and then use shared memory for the tiles of A and B.
But note: the shared memory copy must be done by the entire block, so we need to coordinate.
We can generate:
code
For GPU:
__global__ void kernel(float* A, float* B, float* C, ...) {
__shared__ float As[BLOCK_I][BLOCK_K];
__shared__ float Bs[BLOCK_K][BLOCK_J];
int bx = blockIdx.x; int by = blockIdx.y;
int tx = threadIdx.x; int ty = threadIdx.y;
for (int i0 = 0; i0 < M/BLOCK_I; i0++) {
for (int j0 = 0; j0 < N/BLOCK_J; j0++) {
// load tile
for (int k0 = 0; k0 < K/BLOCK_K; k0++) {
As[ty][tx] = A[(i0*BLOCK_I+ty)*K + (k0*BLOCK_K+tx)];
Bs[ty][tx] = B[(k0*BLOCK_K+ty)*N + (j0*BLOCK_J+tx)];
__syncthreads();
for (int k1 = 0; k1 < BLOCK_K; k1++) {
for (int j1 = 0; j1 < BLOCK_J; j1++) {
// compute using As and Bs
}
}
__syncthreads();
}
}
}
}
This is one example.
So we need to generate:
code
- The loop nest for the grid (i0, j0) and block (inner loops) and then the reduction (k0 and the inner k1).
- And we need to insert the shared memory loads and synchronization.
How to represent this in the IR?
We can have:
code
The original computation:
for i in 0..M:
for j in 0..N:
C[i,j] = 0
for k in 0..K:
C[i,j] += A[i,k] * B[k,j]
Then we tile:
for i0 in 0..M/si:
for i1 in 0..si:
for j0 in 0..N/sj:
for j1 in 0..sj:
for k0 in 0..K/sk:
for k1 in 0..sk:
C[..., ...] += A[..., ...] * B[..., ...]
Then we allocate shared memory for A and B at the (i0, j0, k0) level? Actually, we want to load a tile of A and B for the current (i0, j0) and then iterate over k0.
But note: the tile of A we need is for the current i0 and the entire k range? Actually, for each k0 we load a tile of A and B.
So we might have:
for i0 in 0..M/si:
for j0 in 0..N/sj:
// load tile of A for (i0, all k) and B for (all k, j0) -> but we tile k too.
Alternatively, we tile all three dimensions and then:
for i0 in 0..M/si:
for j0 in 0..N/sj:
for k0 in 0..K/sk:
// load tile of A: [i0*si:(i0+1)*si, k0*sk:(k0+1)*sk] and B: [k0*sk:(k0+1)*sk, j0*sj:(j0+1)*sj] into shared memory.
// then compute the inner product of the tiles.
So we need to represent the shared memory tiles and the computation using them.
We can do:
code
Introduce a new tensor stage for As and Bs (shared memory) that is computed by loading from A and B.
Then the computation uses As and Bs.
The schedule:
- Compute As and Bs at the granularity of (i0, j0, k0) but then we want to reuse As and Bs for multiple (i1, j1) in the inner loops.
Actually, we want to load a tile of A and B for the current (i0, j0) and then iterate over k0 and the inner k1.
So:
s = te.create_schedule(C.op)
As = s.cache_read(A, "shared", [i0, j0, k0]) # but note: the cache_read in TVM is at a certain place in the schedule.
In TVM:
s[As].compute_at(s[C], k0) # meaning that the shared memory tile for A is computed at the granularity of the k0 loop in C.
Then, in the code generation, when we generate the code for C, we see that A is replaced by As, and As is computed by loading from A at the current (i0, j0, k0) and inner indices.
So we need to represent:
code
- The computation graph with multiple stages.
Therefore, we need to change our IR to be a DAG of operations, each producing a tensor, and then we schedule each operation.
Steps:
code
Algorithmic IR: DAG of tensor computations.
Then, we apply a schedule to each operation (or to the whole DAG?).
Given the complexity, we might limit to a single operation (like matmul) for the initial design.
But note: we might have multiple operations (like conv2d + relu).
So we need to support a DAG.
Given the above, let's design a simple pipeline for a single operation (matmul) and then extend to DAG.
We'll assume:
code
- The operation is represented as a loop nest with reduction.
- We have a scheduling language that can:
split(loop, factor) -> (outer, inner)
reorder(loops...)
parallel(loop)
vectorize(loop)
bind(loop, thread_info) # for GPU: blockIdx.x, threadIdx.x, etc.
- And for GPU, we can also:
cache_read(tensor, scope) # create a new stage that reads from the tensor and stores in the given scope (shared, local, etc.)
cache_write(tensor, scope)
- And then we can set the compute_at for these cache stages.
But note: cache_read and cache_write create new stages.
So the IR must support multiple stages.
We can represent:
code
Function:
inputs: list of tensors (with shapes)
outputs: list of tensors
stages: list of Stage
Stage:
- name
- iteration domain: list of (var, range)
- computation: expression for each element of the output tensor (if it's a compute stage) or a computation that loads from another tensor (if it's a cache stage).
- memory scope: where the tensor is stored (global, shared, local, etc.)
Then the schedule:
code
- We start with a default schedule (the naive nested loops).
- Then we apply transformations:
split(stage, loop_var, factor) -> (outer_var, inner_var) and update the stage's iteration domain.
reorder(stage, [var1, var2, ...])
parallel(stage, loop_var)
vectorize(stage, loop_var, factor)
bind(stage, loop_var, axis) # axis: blockIdx.x, threadIdx.x, etc.
cache_read(stage, tensor, scope) -> creates a new stage that reads from the tensor at a certain granularity (which is set by compute_at).
cache_write(stage, tensor, scope) -> similarly.
compute_at(stage, loop_var) # set the granularity at which the stage is computed.
- The schedule also sets the layout of tensors? Maybe not, we assume row-major.
Then, the lowering:
code
For CPU:
- We generate nested loops for the stages, with OpenMP for parallel loops and SIMD for vectorized loops.
For GPU:
- We generate a kernel function with the thread and block bindings, and we use shared memory for stages that are in the shared scope.
But note: the cache_read stage for shared memory must be computed by the entire block, so we set:
code
s[As].compute_at(s[C], k0) # meaning that for each (i0, j0, k0) in the outer loops of C, we compute the entire tile of As.
Then, when generating the code for C, we see that A is replaced by As, and As is computed by loading from A at the current (i0, j0, k0) and the inner indices (i1, k1) for the tile.
How do we represent the computation of As?
code
As[i1, k1] = A[i0*si + i1, k0*sk + k1]
So the iteration domain of As is (i1, k1) with ranges (si, sk).
Then, we set the compute_at to the k0 loop in C? Actually, in TVM, we compute_at the k0 loop of C, so As is computed for each (i0, j0, k0) but note: As does not depend on j0, so we compute it at the k0 loop.
But then we have to load As for each (i1, k1) in the tile.
This is getting detailed.
Given the time, we might not implement the full cache_read mechanism.
Instead, for GPU, we can have a fixed pattern:
code
We tile the loops and then:
- The outer loops (i0, j0) are bound to grid.
- The next set of loops (i1, j1) are bound to block (or thread?).
- We then load the tiles of A and B for the current (i0, j0) and the entire k range? Actually, we tile k too.
We can have:
for i0 in grid_i:
for j0 in grid_j:
for k0 in 0..K/sk:
// load tile of A: [i0*si:(i0+1)*si, k0*sk:(k0+1)*sk] and B: [k0*sk:(k0+1)*sk, j0*sj:(j0+1)*sj] into shared memory.
for i1 in 0..si:
for j1 in 0..sj:
for k1 in 0..sk:
// compute using shared memory
But note: we are iterating over k0 and then k1, so the reduction is over k0*sk + k1.
So the schedule:
- Tile i and j by (si, sj) and k by (sk, ?) but note: we don't split k into two? Actually, we have:
i0, i1, j0, j1, k0, k1
- Bind i0 and j0 to grid (blockIdx.x and blockIdx.y? but note: we have two dimensions for grid and two for block?).
We can bind:
blockIdx.x -> i0
blockIdx.y -> j0
threadIdx.x -> j1 (or i1? we need to decide the thread layout)
And then we have:
for i0 in 0..M/si:
for j0 in 0..N/sj:
for k0 in 0..K/sk:
// load tile:
// As[i1][k1] = A[i0*si + i1, k0*sk + k1] for i1 in 0..si, k1 in 0..sk
// Bs[k1][j1] = B[k0*sk + k1, j0*sj + j1] for k1 in 0..sk, j1 in 0..sj
for i1 in 0..si:
for j1 in 0..sj:
for k1 in 0..sk:
// compute
But note: the inner loops (i1, j1, k1) are over the tile, and we want to parallelize the i1 and j1 by threads? Then we have:
threadIdx.x -> j1
threadIdx.y -> i1
and then k1 is the reduction within the thread? But then we are not using the entire block to load the shared memory? We need to load the shared memory by the entire block.
Actually, the loading of shared memory should be done by all threads. So we have:
for i1 in 0..si:
for j1 in 0..sj:
// each thread loads one element of As and one of Bs? But then we need to load the entire tile.
We can have:
for i1 in 0..si:
for j1 in 0..sj:
for k1 in 0..sk:
// but then we have 3D thread block? We are limited to 3D.
We can flatten the threads:
Let the thread block be 2D: (tx, ty) and then we map:
tx -> j1 and k1? We need to load a 2D tile of A (si x sk) and a 2D tile of B (sk x sj). We can load A by having (i1, k1) and B by (k1, j1). We can use a 2D thread block for A and a separate 2D for B? But we are loading both at the same time.
This is a common problem: we need to load two tiles with the same thread block.
We can do:
Let the thread block be of size (BLOCK_J, BLOCK_I) for the output tile? Actually, we are using two levels of tiling: the grid is for output tiles, and the block is for the inner product of the tiles.
Standard tiling for matmul:
We have:
for i0 in 0..M/BLOCK_I:
for j0 in 0..N/BLOCK_J:
for k0 in 0..K/BLOCK_K:
load A_tile[BLOCK_I][BLOCK_K] and B_tile[BLOCK_K][BLOCK_J] into shared memory.
for i1 in 0..BLOCK_I:
for j1 in 0..BLOCK_J:
for k1 in 0..BLOCK_K:
C_tile[i1][j1] += A_tile[i1][k1] * B_tile[k1][j1]
And then we map:
blockIdx.x -> i0
blockIdx.y -> j0
threadIdx.x -> j1
threadIdx.y -> i1
and then we have a 2D thread block.
But then the loading of A_tile and B_tile must be done by the entire block. We can do:
for k1 in 0..BLOCK_K:
// each thread loads one element of A_tile and one of B_tile? But we have BLOCK_I * BLOCK_J threads, but we need to load BLOCK_I*BLOCK_K for A and BLOCK_K*BLOCK_J for B.
We can have each thread load multiple elements.
Alternatively, we can have the thread block be 3D: (BLOCK_I, BLOCK_J, BLOCK_K) but then we are limited by the number of threads.
Typically, we use a 2D thread block and then each thread loads a contiguous segment of the k dimension.
Given the complexity, let's stick to a simple schedule for GPU:
- Tile the output dimensions (i, j) by (BLOCK_I, BLOCK_J) and the reduction dimension (k) by BLOCK_K.
- The outer loops (i0, j0) are bound to grid (with gridDim.x = ceil(M/BLOCK_I), gridDim.y = ceil(N/BLOCK_J)).
- The inner loops (i1, j1) are bound to thread (with blockDim.x = BLOCK_J, blockDim.y = BLOCK_I). Note: we swap the dimensions so that threadIdx.x is for j and threadIdx.y for i? Actually, we can choose.
- Then we have a loop over k0 (the outer reduction) and then we load the tiles for the current k0.
- Then we have an inner loop over k1 (the inner reduction) and we compute the product.
- The loading of the tiles must be done by all threads. We can do:
for k1 in 0..BLOCK_K:
// each thread loads one element of A and one of B? But we have BLOCK_I*BLOCK_J threads, but we need to load BLOCK_I*BLOCK_K for A and BLOCK_K*BLOCK_J for B.
We can flatten the thread block to be 1D and then each thread loads multiple elements? Or we can have a 3D thread block? Let's not get into that.
Given the time, we will assume that the thread block is 2D and we load the tiles by having each thread load one element of the tile for A and one for B, but then we need to loop over the k dimension for loading? Actually, we can load the entire tile for the current k0 by having each thread load one element of A and one of B for the current k1? But then we need to loop over k1 in the loading? That would be inefficient.
Instead, we can load the entire tile for A and B for the current k0 by having each thread load a column of A and a row of B?
Let's define:
A_tile[i1][k1] and B_tile[k1][j1]
We have:
i1 in 0..BLOCK_I, j1 in 0..BLOCK_J, k1 in 0..BLOCK_K.
We have BLOCK_I * BLOCK_J threads.
We can assign:
For A_tile:
thread (i1, j1) loads A_tile[i1][k1] for all k1? That would be BLOCK_K loads per thread.
So:
for k1 in 0..BLOCK_K:
A_tile[i1][k1] = A[(i0*BLOCK_I + i1)*K + (k0*BLOCK_K + k1)]
B_tile[k1][j1] = B[(k0*BLOCK_K + k1)*N + (j0*BLOCK_J + j1)]
Then we synchronize.
Then we compute:
for k1 in 0..BLOCK_K:
C_tile[i1][j1] += A_tile[i1][k1] * B_tile[k1][j1]
This is a standard approach.
So the scheduled loop nest for GPU:
code
for i0 in 0..M/BLOCK_I:
for j0 in 0..N/BLOCK_J:
for k0 in 0..K/BLOCK_K:
// load tiles
for i1 in 0..BLOCK_I:
for j1 in 0..BLOCK_J:
for k1 in 0..BLOCK_K:
A_tile[i1][k1] = A[...]
B_tile[k1][j1] = B[...]
__syncthreads()
for i1 in 0..BLOCK_I:
for j1 in 0..BLOCK_J:
float sum = 0;
for k1 in 0..BLOCK_K:
sum += A_tile[i1][k1] * B_tile[k1][j1]
C[...] = sum # but note: we are accumulating over k0? Actually, we are doing a reduction over k0 and k1.
Wait, we are missing the reduction over k0? In the original, we had:
C[i,j] = sum_{k} A[i,k] * B[k,j]
We split k into k0 and k1, so:
for k0 in 0..K/BLOCK_K:
for k1 in 0..BLOCK_K:
... += ...
So we need to accumulate over k0 and k1.
We can do:
Initialize C_tile[i1][j1] to 0 at the beginning of (i0, j0).
Then for each k0:
load tiles
compute the inner product and add to C_tile.
Then after all k0, write C_tile to global memory.
So:
code
for i0 in 0..M/BLOCK_I:
for j0 in 0..N/BLOCK_J:
float C_tile[BLOCK_I][BLOCK_J] = 0;
for k0 in 0..K/BLOCK_K:
// load A_tile and B_tile
for i1 in 0..BLOCK_I:
for j1 in 0..BLOCK_J:
float sum = 0;
for k1 in 0..BLOCK_K:
sum += A_tile[i1][k1] * B_tile[k1][j1];
C_tile[i1][j1] += sum;
// write C_tile to C
But then we are computing the entire tile of C for (i0, j0) in registers? That might be too big if BLOCK_I and BLOCK_J are large.
We can accumulate in registers per thread? Each thread (i1, j1) is responsible for one element of C_tile.
So:
float sum = 0;
for k0 in 0..K/BLOCK_K:
// load A_tile and B_tile for this k0 (by all threads)
for k1 in 0..BLOCK_K:
sum += A_tile[i1][k1] * B_tile[k1][j1];
C[...] = sum;
But note: we are loading the same tile of A and B for each k0? Actually, for each k0 we load a different tile of A and B.
So we need to load the tiles for each k0.
And then we accumulate over k1 for that k0.
So:
for i0 in ...:
for j0 in ...:
float sum = 0;
for k0 in ...:
// load A_tile and B_tile for (i0, j0, k0)
for k1 in ...:
sum += A_tile[i1][k1] * B_tile[k1][j1];
C[...] = sum;
But then we are not reusing the shared memory across k0? Actually, we are: for each k0 we load new tiles and then we use them for the inner k1 loop.
This is the standard tiled matmul.
So the schedule for GPU:
code
- Split i and j by (BLOCK_I, BLOCK_J) -> (i0, i1) and (j0, j1)
- Split k by (BLOCK_K, ?) -> (k0, k1) but note: we want to use shared memory for the inner k1? Actually, we tile k by (BLOCK_K, 1) and then we have:
i0, i1, j0, j1, k0, k1
- Then we bind:
i0 -> blockIdx.x
j0 -> blockIdx.y
i1 -> threadIdx.y
j1 -> threadIdx.x
- Then we have:
for i0 in 0..M/BLOCK_I:
for j0 in 0..N/BLOCK_J:
float reg = 0;
for k0 in 0..K/BLOCK_K:
// load A_tile[i1][k1] and B_tile[k1][j1] for k1 in 0..BLOCK_K
// we are going to load the entire tile for this k0 by the entire block.
for k1 in 0..BLOCK_K:
// load A_tile[i1][k1] and B_tile[k1][j1] from global memory.
__syncthreads()
for k1 in 0..BLOCK_K:
reg += A_tile[i1][k1] * B_tile[k1][j1];
__syncthreads()
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] = reg;
But note: we are using shared memory for A_tile and B_tile, and we are loading them for each k0.
This is a common pattern.
So we need to represent:
code
- The loop nest with 6 loops: i0, i1, j0, j1, k0, k1.
- And then we bind i0 and j0 to grid, i1 and j1 to thread.
- And we allocate shared memory for A_tile and B_tile of size (BLOCK_I, BLOCK_K) and (BLOCK_K, BLOCK_J).
- And we insert __syncthreads() after loading and after computing? Actually, we need to synchronize after loading because all threads must finish loading before any thread uses the shared memory.
How to represent this in the IR?
We can have:
code
Stage for the output C (or the final accumulation).
But we also have intermediate stages for A_tile and B_tile? Actually, they are just shared memory buffers.
We can represent:
- The computation of C as a reduction over k.
- We have two additional buffers (shared memory) for A and B tiles.
The schedule:
- We split the loops.
- We set the compute scope for A_tile and B_tile to be at the k0 loop? Actually, we compute them at the granularity of k0, and they are used in the inner loops (k1).
So:
s[A_tile].compute_at(s[C], k0)
s[B_tile].compute_at(s[C], k0)
Then, when generating code for C, we see that A and B are replaced by A_tile and B_tile, and we generate code for A_tile and B_tile that loads from global memory at the current (i0, j0, k0) and the inner indices (i1, k1) and (k1, j1).
So we need to be able to represent:
code
- A_tile and B_tile as new stages (with shared memory scope) that are computed at the k0 loop of C.
This requires the IR to have:
code
- Multiple stages (each with its own iteration domain and computation).
- The ability to set the compute_at relationship between stages.
Given the complexity, we might decide to design a simpler IR that only supports one stage (the output) and then we manually insert the shared memory loads and synchronizations.
But then we lose the ability to autotune the tiling and the use of shared memory.
Given the time, we will design a minimal viable product:
code
- We assume the operation is a single matmul.
- We have a schedule that:
1. Tiles the output loops (i, j) by (BLOCK_I, BLOCK_J).
2. Tiles the reduction loop (k) by (BLOCK_K, 1) -> so we have (k0, k1).
3. Binds the outer tiled loops to grid and the inner tiled loops to thread.
4. Inserts two shared memory stages for A and B tiles, and computes them at the k0 loop.
5. Then the computation of C uses the shared memory stages and accumulates over k1.
- We generate code accordingly.
Then we can autotune the tile sizes (BLOCK_I, BLOCK_J, BLOCK_K).
Code Generation:
For CPU:
code
We generate nested loops with OpenMP for the outer parallel loops and SIMD for the inner vectorized loops.
Example:
#pragma omp parallel for
for i0 in 0..M/BLOCK_I:
for i1 in 0..BLOCK_I:
for j0 in 0..N/BLOCK_J:
for j1 in 0..BLOCK_J:
float sum = 0;
for k0 in 0..K/BLOCK_K:
for k1 in 0..BLOCK_K:
sum += A[i0*BLOCK_I+i1, k0*BLOCK_K+k1] * B[k0*BLOCK_K+k1, j0*BLOCK_J+j1];
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] = sum;
But note: we might want to vectorize the inner loop over k1? Actually, we are accumulating over k1, so we cannot vectorize the inner loop easily. We can vectorize the j1 loop? But j1 is the inner loop of the output.
Alternatively, we can change the loop order to have the vectorized loop innermost.
We might have:
for i0 in ...:
for j0 in ...:
for k0 in ...:
for i1 in ...:
for j1 in ...:
for k1 in ...:
But then we are not using cache blocking effectively.
We might want to have the inner loops be contiguous in memory.
Given the time, we will generate the code in the order of the schedule.
For GPU:
code
We generate:
__global__ void kernel(float* A, float* B, float* C, int M, int N, int K, int BLOCK_I, int BLOCK_J, int BLOCK_K) {
__shared__ float A_tile[BLOCK_I][BLOCK_K];
__shared__ float B_tile[BLOCK_K][BLOCK_J];
int i0 = blockIdx.x;
int j0 = blockIdx.y;
int i1 = threadIdx.y;
int j1 = threadIdx.x;
int i = i0 * BLOCK_I + i1;
int j = j0 * BLOCK_J + j1;
float sum = 0;
for (int k0 = 0; k0 < K/BLOCK_K; k0++) {
// load tile
for (int k1 = 0; k1 < BLOCK_K; k1++) {
A_tile[i1][k1] = A[i*K + k0*BLOCK_K+k1];
B_tile[k1][j1] = B[(k0*BLOCK_K+k1)*N + j];
}
__syncthreads();
for (int k1 = 0; k1 < BLOCK_K; k1++) {
sum += A_tile[i1][k1] * B_tile[k1][j1];
}
__syncthreads();
}
if (i < M && j < N) {
C[i*N + j] = sum;
}
}
Note: we assume row-major.
Autotuning:
We can try different values for BLOCK_I, BLOCK_J, BLOCK_K.
We can search over a grid of possible sizes (e.g., powers of 2) and measure the runtime.
We need a cost model? We can use empirical tuning.
We can run the kernel multiple times and take the minimum time.
We need to generate the kernel for each set of parameters and then run it.
This is expensive, but for a single operation it might be acceptable.
Test Harness:
We generate a host program that:
code
- Allocates and initializes A, B, and C (for reference) on the host (CPU memory).
- For CPU: runs the CPU kernel and checks the result.
- For GPU: copies A and B to device, runs the kernel, copies C back, and checks the result.
We can generate two separate executables: one for CPU and one for GPU.
Or we can generate one executable that has both and we select at runtime.
We'll generate one executable that takes a flag (--cpu or --gpu) and runs the appropriate kernel.
The test harness will also measure the time.
Given the time, we will assume that the shared memory stages are created by the schedule for GPU, and for CPU we don't use shared memory.
So we design:
code
IR for the algorithm:
We have a loop nest for the computation of C.
Schedule:
We have a list of transformations:
split(loop_var, factor) -> (outer, inner)
reorder([var1, var2, ...])
parallel(loop_var)
vectorize(loop_var, factor) # for CPU
bind(loop_var, axis) # for GPU: axis can be blockIdx.x, threadIdx.x, etc.
cache_read(tensor, scope, [loop_vars]) # for GPU: create a new stage that reads from the tensor and is computed at the granularity of the given loop_vars.
Then, after applying the schedule, we have:
- A loop nest for C (with possibly fewer loops because we might have split and then the inner loops are now used for the shared memory stages? Actually, the shared memory stages have their own loop nests.
We need to represent the entire schedule, including the new stages.
Given the complexity, we might limit to:
code
- Only one output stage (C) and two shared memory stages (A_shared, B_shared) for GPU.
- For CPU, we don't have shared memory stages.
So we design:
code
Schedule for GPU:
s = Schedule()
# Tile the loops
s.split('i', factor=BLOCK_I) -> (i0, i1)
s.split('j', factor=BLOCK_J) -> (j0, j1)
s.split('k', factor=BLOCK_K) -> (k0, k1)
# Bind
s.bind('i0', 'blockIdx.x')
s.bind('j0', 'blockIdx.y')
s.bind('i1', 'threadIdx.y')
s.bind('j1', 'threadIdx.x')
# Create shared memory stages
A_shared = s.cache_read('A', 'shared', ['k0']) # compute at k0
B_shared = s.cache_read('B', 'shared', ['k0'])
Then, in the computation of C, we replace A with A_shared and B with B_shared.
Then, when generating code for C, we have:
for i0 in ...:
for j0 in ...:
for k0 in ...:
// compute A_shared at (i0, j0, k0) -> iteration domain: (i1, k1) for A_shared? Actually, A_shared is computed at the granularity of k0, so its iteration domain is (i1, k1) and it depends on i0 and k0? Wait, we need to think.
The cache_read in TVM:
s[shared].compute_at(s[C], k0)
means that the shared stage is computed for each (i0, j0, k0) and its iteration domain is the remaining loops of C that are inside k0? Actually, in TVM, the compute_at means that the shared stage is computed at the granularity of the loop k0 in C, meaning that for each value of k0, we compute the entire tile of shared memory.
So the iteration domain of A_shared is (i1, k1) and it depends on i0 and k0 (the outer loops). So:
A_shared[i1, k1] = A[i0*BLOCK_I+i1, k0*BLOCK_K+k1]
Similarly for B_shared.
So we need to represent:
code
Stage for C:
vars: [i0, i1, j0, j1, k0, k1]
body:
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] += A_shared[i1, k1] * B_shared[k1, j1]
But note: the reduction is over k0 and k1. We have split k into k0 and k1, and we are accumulating over both.
Actually, we are accumulating over k0 and k1:
for k0 in ...:
for k1 in ...:
... += ...
So we need to initialize the accumulation at the beginning of (i0, j0) and then accumulate over k0 and k1.
We can represent:
Stage C:
init: C[i1, j1] = 0 [but note: the indices of C are (i0*BLOCK_I+i1, j0*BLOCK_J+j1), so we need to write to the global C]
then for each k0:
load A_shared and B_shared (which are computed at the current k0)
for k1 in ...:
C[i1, j1] += A_shared[i1, k1] * B_shared[k1, j1]
But note: the A_shared and B_shared are computed at the current k0 and for the current (i0, j0). So they are the same for all (i1, j1) in the tile? Actually, A_shared depends on i1 and k1, and B_shared on k1 and j1.
So we can write:
for i0 in ...:
for j0 in ...:
float reg[BLOCK_I][BLOCK_J] = 0; // in registers? Actually, each thread (i1, j1) has its own register.
for k0 in ...:
// load A_shared and B_shared (by the entire block)
for i1 in ...:
for j1 in ...:
for k1 in ...:
reg[i1][j1] += A_shared[i1][k1] * B_shared[k1][j1];
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] = reg[i1][j1];
So we don't need to write to a shared memory for C.
Therefore, we don't need a stage for C_tile. We just accumulate in registers.
So the stage for C is:
code
vars: [i0, i1, j0, j1, k0, k1]
body:
if (first occurrence of (i0, i1, j0, j1)) then set C[...] = 0? Actually, we are accumulating over k0 and k1, so we need to initialize at the beginning of (i0, j0). We can do:
for i0 in ...:
for j0 in ...:
float sum = 0;
for k0 in ...:
for k1 in ...:
sum += A_shared[i1][k1] * B_shared[k1][j1];
C[...] = sum;
But note: the shared memory stages A_shared and B_shared are computed at each k0, and they are used in the inner k1 loop.
So we can represent:
code
Stage C:
vars: [i0, i1, j0, j1, k0, k1]
body:
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] = A_shared[i1, k1] * B_shared[k1, j1] with a reduction over k0 and k1.
But then we have two reductions: over k0 and k1? Actually, k0 is an outer loop and k1 is inner. We are doing:
for k0:
load shared memory for k0
for k1:
sum += ...
So we have a reduction over k0 and k1.
inputs: list of Tensors (with shapes and names)
outputs: list of Tensors (with shapes and names)
stages: list of Stage
Stage:
code
- name
- tensor: the tensor that this stage computes (with shape)
- memory_scope: (global, shared, local, etc.)
- loop_vars: list of (var, range)
- computation: an expression tree (let's define Expression)
Expression:
code
- Literal
- VarRef: (var_name) # refers to a loop variable
- TensorAccess: (tensor_name, list of indices) # indices are Expressions
- BinaryOp: (op, left, right)
- Reduction: (reduce_op, reduce_var, reduce_range, body)
Example for C:
code
Stage C:
tensor: C
memory_scope: global
loop_vars: [i0 (0..M/BLOCK_I), i1 (0..BLOCK_I), j0 (0..N/BLOCK_J), j1 (0..BLOCK_J), k0 (0..K/BLOCK_K), k1 (0..BLOCK_K)]
computation:
Assignment(
lhs = TensorAccess(C, [i0*BLOCK_I+i1, j0*BLOCK_J+j1]),
rhs = Reduce(
reduce_op = Sum,
reduce_var = k0, # but we have two reduction variables? We can have nested reductions.
reduce_range = (0..K/BLOCK_K),
body = Reduce(
reduce_op = Sum,
reduce_var = k1,
reduce_range = (0..BLOCK_K),
body = BinaryOp(Mul,
TensorAccess(A_shared, [i1, k1]),
TensorAccess(B_shared, [k1, j1])
)
)
)
)
But note: the A_shared and B_shared stages are computed at the granularity of k0? Actually, they are computed at the same k0 as the outer reduction?
We have:
Stage A_shared:
tensor: A_shared
memory_scope: shared
loop_vars: [i1 (0..BLOCK_I), k1 (0..BLOCK_K)]
computation:
Assignment(
lhs = TensorAccess(A_shared, [i1, k1]),
rhs = TensorAccess(A, [i0*BLOCK_I+i1, k0*BLOCK_K+k1])
)
And similarly for B_shared.
And we set the compute_at for A_shared and B_shared to the k0 loop of C.
So we need to represent the compute_at relationship.
In the Function, we can have:
code
stages: [C, A_shared, B_shared]
and then a schedule that says:
- A_shared.compute_at(C, k0)
- B_shared.compute_at(C, k0)
Then, when generating code for C, we generate the loops for C, and when we encounter the use of A_shared, we generate the loop nest for A_shared at the current k0.
This is similar to TVM's compute_at.
Given the complexity, we might decide to implement a simplified version without the full IR and schedule.
Instead, we can have:
code
- A high-level function that describes the operation (like matmul) and then we have a set of schedule parameters (tile sizes, bindings, etc.)
- Then we generate code based on those parameters.
But then we cannot have a general IR.
Given the time, I think we should design a minimal IR and pipeline that works for matmul and then extend.
Let's define:
code
IR for a single operation:
Operation:
- type: "matmul"
- shape: (M, K) for A, (K, N) for B, (M, N) for C.
Schedule:
- tile_sizes: (BLOCK_I, BLOCK_J, BLOCK_K)
- for GPU: use_shared = True
- for CPU: use_vectorize = True (and vector_width)
Then we generate code accordingly.
But then we lose the ability to handle arbitrary operations.
Given the assignment, we are asked to design a compiler pipeline that generates both CPU and GPU kernels from the same IR. So we need an IR.
We'll design a simple IR that can represent the loop nest for matmul and then we can apply the schedule.
We'll have:
code
LoopNest:
loops: list of Loop
body: Block of statements
Loop:
var: string
range: (start, end) # both are Expressions
Block:
statements: list
Statement:
- Assignment(lhs, rhs)
- For(loop, body)
Expression:
- Var(var)
- Const(value)
- BinaryOp(op, left, right)
- TensorRef(tensor, indices)
TensorRef:
tensor: string
indices: list of Expressions
Example for matmul:
code
For(i0, (0, M/BLOCK_I)):
For(i1, (0, BLOCK_I)):
For(j0, (0, N/BLOCK_J)):
For(j1, (0, BLOCK_J)):
For(k0, (0, K/BLOCK_K)):
For(k1, (0, BLOCK_K)):
Assignment(
TensorRef(C, [i0*BLOCK_I+i1, j0*BLOCK_J+j1]),
BinaryOp('+',
TensorRef(C, [i0*BLOCK_I+i1, j0*BLOCK_J+j1]),
BinaryOp('*',
TensorRef(A, [i0*BLOCK_I+i1, k0*BLOCK_K+k1]),
TensorRef(B, [k0*BLOCK_K+k1, j0*BLOCK_J+j1])
)
)
)
But note: this is a reduction over k0 and k1. We need to initialize C to 0? Actually, we are doing:
C[...] = C[...] + ...
so we need to initialize C to 0 at the beginning.
We can have:
For(i0, ...):
For(i1, ...):
For(j0, ...):
For(j1, ...):
Assignment(TensorRef(C, [...]), Const(0))
For(k0, ...):
For(k1, ...):
Assignment(
TensorRef(C, [...]),
BinaryOp('+', TensorRef(C, [...]), ...)
)
This is a naive way.
Alternatively, we can have a reduction expression.
Given the time, we'll stick to the naive way.
Then, we apply schedule:
code
- We split the loops: we have already split the loops by tile sizes? Actually, in the above we already split.
But we want to start from the full loops and then split.
So we might start from:
For(i, (0, M)):
For(j, (0, N)):
Assignment(TensorRef(C, [i,j]), Const(0))
For(k, (0, K)):
Assignment(
TensorRef(C, [i,j]),
BinaryOp('+', TensorRef(C, [i,j]), BinaryOp('*', TensorRef(A, [i,k]), TensorRef(B, [k,j])))
)
Then we apply:
s.split('i', BLOCK_I) -> (i0, i1)
s.split('j', BLOCK_J) -> (j0, j1)
s.split('k', BLOCK_K) -> (k0, k1)
Then we get the loop nest above.
Then we bind:
code
For CPU: we might parallelize i0 and j0? Actually, we can parallelize i0 and j0? But note: we are writing to C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] and there might be race conditions if two threads write to the same element? We are splitting i and j by BLOCK_I and BLOCK_J, so each (i0, i1, j0, j1) is unique? Actually, i0 and i1 together cover i, and j0 and j1 together cover j. So if we parallelize i0 and j0, then each thread will handle a tile of C and there is no race condition.
So we can parallelize the outer loops (i0 and j0) for CPU.
For GPU: we bind i0 to blockIdx.x and j0 to blockIdx.y, and i1 to threadIdx.y and j1 to threadIdx.x.
Then for GPU, we need to insert shared memory for A and B.
code
We create two new tensors: A_shared and B_shared.
We create new stages for them:
For(k0 in 0..K/BLOCK_K):
For(i1 in 0..BLOCK_I):
For(k1 in 0..BLOCK_K):
Assignment(TensorRef(A_shared, [i1, k1]), TensorRef(A, [i0*BLOCK_I+i1, k0*BLOCK_K+k1]))
For(j1 in 0..BLOCK_J):
For(k1 in 0..BLOCK_K):
Assignment(TensorRef(B_shared, [k1, j1]), TensorRef(B, [k0*BLOCK_K+k1, j0*BLOCK_J+j1]))
And then we replace A and B in the computation of C with A_shared and B_shared.
And we set that these assignments for A_shared and B_shared are computed at the granularity of k0 in the C loop.
So we need to represent:
code
- Multiple stages (C, A_shared, B_shared) and the compute_at relationship.
Given the time, we might hardcode the shared memory insertion for matmul.
So we design:
code
IR:
Function:
name: "matmul"
inputs: [A, B]
output: C
schedule: Schedule
Schedule:
- tile_sizes: (BLOCK_I, BLOCK_J, BLOCK_K)
- target: "cpu" or "gpu"
- for GPU:
use_shared: True
Then we generate code:
If CPU:
generate loops with the given tile sizes and parallelize the outer loops (i0, j0) with OpenMP.
If GPU:
generate kernel with the tile sizes and shared memory.
Then we can autotune by trying different tile sizes.
This is a very limited design, but it works for matmul.
We can extend to other operations by having a more general IR, but for the purpose of this assignment, we can do matmul.
Test Harness:
We generate:
code
int main() {
// allocate A, B, C on host
// initialize A and B with random values
// compute reference C on CPU (naive)
// run the kernel (either CPU or GPU) and check against reference.
}
For GPU, we also need to allocate device memory and copy.
We can write a Python script that:
- Generates the CPU and GPU code for a given set of tile sizes.
- For CPU: we compile with OpenMP and run with different numbers of threads? Actually, the tile sizes are the same as for GPU? We might want to tune separately.
- We can search over a grid of possible tile sizes (powers of 2) and measure the runtime.
We'll do:
For each set of (BLOCK_I, BLOCK_J, BLOCK_K) in some set:
generate the code
compile and run
record the time
Then pick the best.
For CPU, we might also want to tune the OpenMP schedule and the vectorization factor? But we are using the tile sizes to control the cache blocking and vectorization? Actually, we are not vectorizing explicitly. We are relying on the compiler to vectorize the inner loop (k1) if possible? But the inner loop is over k1 and we are accumulating, so the compiler might not vectorize.
We can change the loop order to have the vectorizable loop innermost? For example:
for i0 in ...:
for j0 in ...:
for k0 in ...:
for i1 in ...:
for j1 in ...:
for k1 in ...:
... # then we can vectorize the k1 loop? But then we are writing to C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] and reading A and B with k1 as the inner dimension, which is contiguous for A? A is row-major, so A[i, k] is contiguous in k. Similarly, B[k, j] is not contiguous in k (because B is row-major, so B[k, j] is at k*N+j, so k is the outer dimension). So if we make k1 the innermost, then we are accessing A with contiguous k1 (good) but B with non-contiguous k1 (because B is row-major and we are fixing j and varying k, which is the outer dimension). So we want k to be contiguous for B? Actually, B[k, j] is not contiguous in k because the next element in memory for the same j is at (k+1)*N+j, so it's stride N.
So we might want to interchange the loops for B to have j as the inner dimension? But then we break the reduction.
Given the complexity, we will not change the loop order for CPU and rely on the tile sizes to control cache behavior.
We can try to vectorize the inner loop over k1 by using SIMD instructions. We can generate:
for (k1 = 0; k1 < BLOCK_K; k1++) {
sum += A_contiguous * B_contiguous?
}
But note: for the CPU version, we are not using shared memory, so we are accessing A and B directly.
We can change the order to:
for i0 in ...:
for j0 in ...:
for i1 in ...:
for k0 in ...:
for k1 in ...:
for j1 in ...:
... # then we are accessing A[i0*BLOCK_I+i1, k0*BLOCK_K+k1] (contiguous in k1) and B[k0*BLOCK_K+k1, j0*BLOCK_J+j1] (strided by N).
So we can vectorize the k1 loop? But then we are accumulating over k1 and j1? Actually, we have:
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] = sum over k0 and k1 of A[i0*BLOCK_I+i1, k0*BLOCK_K+k1] * B[k0*BLOCK_K+k1, j0*BLOCK_J+j1]
If we interchange j1 and k1, we get:
for j1 in ...:
sum = 0;
for k0 in ...:
for k1 in ...:
sum += A[...] * B[...]
C[...] = sum;
Then we can vectorize the inner loop over k1? But then we are still strided for B.
Alternatively, we can vectorize the j1 loop? Then we would load a vector of B for the same k and different j, and then multiply by a vector of A? But A is the same for all j in the tile? Actually, for a fixed i and k, A is a scalar.
We can do:
for j1 in vectorized:
float b = B[k, j0*BLOCK_J+j1];
sum += a * b;
So we can vectorize the j1 loop.
So we can change the loop order to:
for i0 in ...:
for j0 in ...:
for i1 in ...:
for k0 in ...:
for k1 in ...:
float a = A[i0*BLOCK_I+i1, k0*BLOCK_K+k1];
for j1 in 0..BLOCK_J:
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] += a * B[k0*BLOCK_K+k1, j0*BLOCK_J+j1];
But then we are updating C multiple times (by different j1) and we need to initialize C to 0? Actually, we are accumulating over k0 and k1, and for each (i, j) we are accumulating over k. So we can do:
for i0 in ...:
for j0 in ...:
for i1 in ...:
for j1 in ...:
float sum = 0;
for k0 in ...:
for k1 in ...:
sum += A[i0*BLOCK_I+i1, k0*BLOCK_K+k1] * B[k0*BLOCK_K+k1, j0*BLOCK_J+j1];
C[...] = sum;
This is the same as before.
We can interchange j1 and k1 to:
for i0 in ...:
for j0 in ...:
for i1 in ...:
for k0 in ...:
for j1 in ...:
float sum = 0;
for k1 in ...:
sum += A[i0*BLOCK_I+i1, k0*BLOCK_K+k1] * B[k0*BLOCK_K+k1, j0*BLOCK_J+j1];
C[i0*BLOCK_I+i1, j0*BLOCK_J+j1] += sum;
But then we are updating C multiple times (for each k0) and we need to initialize C to 0.
Given the time, we will stick to the first version and not try to vectorize for CPU.
For GPU, we are already using shared memory and vectorization is not needed because we are using one thread per output element and we are accumulating in a register.