Write a fast matrix-free CG solver in taichi
- User
Write a fast matrix-free CG solver in taichi
- Assistant
Write a fast matrix-free CG solver in taichi
Certainly! Below is a comprehensive example of a matrix-free Conjugate Gradient (CG) solver implemented using Taichi, a high-performance, parallel programming language suitable for numerical computations. This example solves a simple 2D Poisson equation using a finite difference stencil as the matrix-free operator.
Matrix-Free Approach: Instead of explicitly storing the matrix, we define a function that performs the matrix-vector multiplication. For the Poisson equation, this involves applying the finite difference Laplacian stencil.
Conjugate Gradient Method: An iterative solver for symmetric positive-definite systems, ideal for large sparse systems where matrix-free methods are beneficial.
Taichi Features: Utilizes Taichi's parallelism and just-in-time (JIT) compilation to optimize performance, especially on GPU devices.
Python 3.7+
Taichi: Install via pip if you haven't already.
pip install taichi
Here's the complete code for the matrix-free CG solver in Taichi:
import taichi as ti
import numpy as np
ti.init(arch=ti.gpu) # Use GPU for acceleration. Switch to ti.cpu if GPU is unavailable.
# Problem Setup: Solve Poisson Equation on a 2D Grid
# The equation: -Δu = f
# Domain: [0, 1] x [0, 1] with Dirichlet boundary conditions (u=0 on boundary)
# Grid size
N = 256 # Number of interior points in each dimension
dx = 1.0 / (N + 1)
# Taichi fields
u = ti.field(dtype=ti.f32, shape=(N, N)) # Solution
f = ti.field(dtype=ti.f32, shape=(N, N)) # Right-hand side
r = ti.field(dtype=ti.f32, shape=(N, N)) # Residual
p = ti.field(dtype=ti.f32, shape=(N, N)) # Search direction
Ap = ti.field(dtype=ti.f32, shape=(N, N)) # A*p
# Initialize f with some function, e.g., f = 1
@ti.kernel
def initialize_f():
for i, j in f:
f[i, j] = 1.0
# Matrix-Free Operator: Apply A*p where A is the Laplacian
@ti.kernel
def apply_A(p_field: ti.template(), Ap_field: ti.template()):
for i, j in p_field:
Ap_field[i, j] = (
4.0 * p_field[i, j]
- p_field[i - 1 if i > 0 else i, j]
- p_field[i + 1 if i < N - 1 else i, j]
- p_field[i, j - 1 if j > 0 else j]
- p_field[i, j + 1 if j < N - 1 else j]
) / (dx * dx)
# Initialize residual r = f - A*u (since u=0 initially, r = f)
@ti.kernel
def compute_initial_residual(r_field: ti.template(), f_field: ti.template(), u_field: ti.template()):
for i, j in r_field:
r_field[i, j] = f_field[i, j]
# Subtract A*u, but u=0 initially
# Compute dot product
@ti.func
def dot_product(a: ti.template(), b: ti.template()) -> ti.f32:
temp = ti.static(ti.var(ti.f32, shape=()))
temp[None] = 0.0
for i, j in a:
ti.atomic_add(temp[None], a[i, j] * b[i, j])
return temp[None]
# CG Solver
def conjugate_gradient(max_iters=1000, tol=1e-6):
# Initialize
initialize_f()
compute_initial_residual(r, f, u)
p.copy_from(r)
rsold = dot_product(r, r)
for iter in range(max_iters):
apply_A(p, Ap)
alpha_num = rsold
alpha_den = dot_product(p, Ap)
if alpha_den == 0:
print("Alpha denominator is zero. Exiting.")
break
alpha = alpha_num / alpha_den
# Update u and r
for i, j in u:
u[i, j] += alpha * p[i, j]
for i, j in r:
r[i, j] -= alpha * Ap[i, j]
rsnew = dot_product(r, r)
print(f"Iter {iter+1}: Residual norm = {np.sqrt(rsnew)}")
if np.sqrt(rsnew) < tol:
break
# Update p
beta = rsnew / rsold
for i, j in p:
p[i, j] = r[i, j] + beta * p[i, j]
rsold = rsnew
# Run the solver
if __name__ == "__main__":
conjugate_gradient()
# Retrieve the solution
u_np = u.to_numpy()
# Optionally, visualize the solution using matplotlib
import matplotlib.pyplot as plt
X, Y = np.meshgrid(np.linspace(0, 1, N), np.linspace(0, 1, N))
plt.figure(figsize=(6, 5))
cp = plt.contourf(X, Y, u_np, levels=50, cmap='viridis')
plt.colorbar(cp)
plt.title('Solution u of Poisson Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Grid Setup: The domain ([0,1]^2) is discretized into an (N \times N) grid with grid spacing dx.
Fields:
u: Solution field.f: Right-hand side of the Poisson equation.r: Residual.p: Search direction.Ap: (A \cdot p), where (A) is the matrix operator.The apply_A kernel applies the Laplacian operator using a finite difference stencil:
[ A \cdot p_{i,j} = \frac{4p_{i,j} - p_{i-1,j} - p_{i+1,j} - p_{i,j-1} - p_{i,j+1}}}{dx^2} ]
This avoids storing the matrix (A), instead computing the product on-the-fly.
Since the initial guess (u=0), the residual (r = f - A \cdot u = f).
A custom dot_product function computes the inner product of two fields using atomic additions for parallel safety.
The CG algorithm iteratively updates the solution u, residual r, and search direction p. Key steps include:
After solving, the solution u is converted to a NumPy array for visualization using matplotlib.
Backend Selection: The ti.init(arch=ti.gpu) directive attempts to use the GPU for acceleration. If you don't have a compatible GPU, switch to ti.cpu.
Vectorization and Parallelism: Taichi automatically parallelizes loops. Ensure that kernels are written without data dependencies to maximize parallel efficiency.
Memory Access Patterns: Optimize data locality by accessing memory in a cache-friendly manner, especially important for GPU performance.
Preconditioning: Implement preconditioning to accelerate convergence.
Boundary Conditions: Extend the solver to handle different types of boundary conditions.
Adaptive Stopping Criteria: Enhance the stopping condition based on relative residuals or other metrics.
Higher Dimensions: Extend the solver to 3D problems by increasing the problem dimensionality.
This example demonstrates how to implement a matrix-free Conjugate Gradient solver in Taichi, leveraging its high-performance capabilities for numerical simulations. By avoiding explicit matrix storage and utilizing Taichi's parallelism, this approach is both memory-efficient and scalable for large problems.
Feel free to modify and extend this code to suit more complex applications or to integrate with other numerical methods!
Not yet included in a published release.