# Taichi fields for 2D vectors and matrices
self.x0 = ti.field(dtype=ti.f32, shape=(rows, cols))
self.b = ti.field(dtype=ti.f32, shape=(rows, cols))
self.V = ti.field(dtype=ti.f32, shape=(n_iter + 1, rows, cols))
self.H = ti.field(dtype=ti.f32, shape=(n_iter + 1, n_iter))
self.w = ti.field(dtype=ti.f32, shape=(rows, cols))
self.beta = ti.field(dtype=ti.f32, shape=())
self.r0 = ti.field(dtype=ti.f32, shape=(rows, cols))
self.diagonal_inv = ti.field(dtype=ti.f32, shape=(rows, cols))
# Kernel for vector subtraction: result = v1 - v2
@ti.kernel
def subtract_vectors(self, v1: ti.template(), v2: ti.template(), result: ti.template()):
for i, j in ti.ndrange(self.rows, self.cols):
result[i, j] = v1[i, j] - v2[i, j]
# Kernel for vector normalization: v /= norm(v)
@ti.kernel
def normalize(self, v: ti.template(), norm: ti.f32):
for i, j in ti.ndrange(self.rows, self.cols):
v[i, j] /= norm
# Kernel for calculating the 2-norm of a vector
@ti.kernel
def norm(self, v: ti.template()) -> ti.f32:
norm_val = 0.0
for i, j in ti.ndrange(self.rows, self.cols):
norm_val += v[i, j] * v[i, j]
return ti.sqrt(norm_val)
# Kernel to copy one vector to another (manual element-by-element copying)
@ti.kernel
def copy_vector(self, src: ti.template(), dst: ti.template(), idx: ti.i32):
for i, j in ti.ndrange(self.rows, self.cols):
dst[idx, i, j] = src[i, j]
# Kernel for dot product with 2D array row access
@ti.kernel
def dot_product_row(self, v1: ti.template(), v2: ti.template(), row: ti.i32) -> ti.f32:
dot = 0.0
for i, j in ti.ndrange(self.rows, self.cols):
dot += v1[i, j] * v2[row, i, j]
return dot
# Kernel for in-place subtraction: v1 -= scalar * v2
@ti.kernel
def subtract_scaled_vector(self, v1: ti.template(), v2: ti.template(), scalar: ti.f32):
for i, j in ti.ndrange(self.rows, self.cols):
v1[i, j] -= scalar * v2[i, j]
# Kernel for dot product
@ti.kernel
def dot_product(self, v1: ti.template(), v2: ti.template()) -> ti.f32:
dot = 0.0
for i, j in ti.ndrange(self.rows, self.cols):
dot += v1[i, j] * v2[i, j]
return dot
# Helper kernel to extract the j-th row from V and store it in a temporary vector
@ti.kernel
def extract_vector_from_V(self, j: ti.i32, temp: ti.template()):
for i, k in ti.ndrange(self.rows, self.cols):
temp[i, k] = self.V[j, i, k]
# Orthogonalization in Python-scope (modified)
def orthogonalize_in_python(self, j):
temp_vec = ti.field(dtype=ti.f32, shape=(self.rows, self.cols))
for i in range(j + 1):
self.extract_vector_from_V(i, temp_vec) # Extract V[i] into temp_vec
self.H[i, j] = self.dot_product(self.w, temp_vec) # Perform dot product
self.subtract_scaled_vector(self.w, temp_vec, self.H[i, j]) # Update w
self.H[j + 1, j] = self.norm(self.w) # Norm of w
self.normalize(self.w, self.H[j + 1, j]) # Normalize w
self.copy_vector(self.w, self.V, j + 1) # Copy w to V[j + 1]
# Function to apply Givens rotations and solve the least squares problem
# Kernel for in-place Givens rotations and solving least squares problem
@ti.kernel
def apply_givens_rotations(self, e1: ti.template(), y: ti.template()):
# Apply Givens rotations and solve the upper triangular system R_n y_n = e1
for j in range(self.n_iter):
rho = self.H[j, j] # diagonal entry of H (R_n)
sigma = self.H[j + 1, j] # sub-diagonal entry of H
c = rho / ti.sqrt(rho**2 + sigma**2)
s = sigma / ti.sqrt(rho**2 + sigma**2)
# Modify the matrix H to reflect the Givens rotation
for k in range(j, self.n_iter):
temp = c * self.H[j, k] + s * self.H[j + 1, k]
self.H[j + 1, k] = -s * self.H[j, k] + c * self.H[j + 1, k]
self.H[j, k] = temp
# Apply the same rotation to e1 (right-hand side vector)
temp_e1 = c * e1[j] + s * e1[j + 1]
e1[j + 1] = -s * e1[j] + c * e1[j + 1]
e1[j] = temp_e1
# Step 2: Solve the upper triangular system R_n y_n = e1 (simulating back substitution)
for i in range(self.n_iter):
rev_i = self.n_iter - 1 - i # Reverse index for back substitution
sum_val = 0.0
for j in range(rev_i + 1, self.n_iter):
sum_val += self.H[rev_i, j] * y[j]
y[rev_i] = (e1[rev_i] - sum_val) / self.H[rev_i, rev_i]
# Kernel for preconditioned matrix-vector multiplication: v' = D^{-1} v
@ti.kernel
def apply_preconditioner(self, v: ti.template(), result: ti.template()):
for i, j in ti.ndrange(self.rows, self.cols):
result[i, j] = self.diagonal_inv[i, j] * v[i, j] # Applying diagonal inverse
# GMRES solver function with Jacobi preconditioner
def gmres_solve(self, b, x0, linear_map, diagonal):
# Set up the preconditioner (diagonal inverse)
for i in range(self.rows):
for j in range(self.cols):
if diagonal[i,j] != 0:
self.diagonal_inv[i, j] = 1.0 / diagonal[i, j] # Inverse of diagonal elements
# Step 1: r0 = b - linear_map(x0)
linear_map(x0, self.r0)
self.subtract_vectors(b, self.r0, self.r0)
# Apply Jacobi preconditioner to r0: r0 = D^{-1} r0
self.apply_preconditioner(self.r0, self.r0)
# Step 2: beta = norm(r0)
beta_value = self.norm(self.r0)
self.beta[None] = beta_value
# Step 3: V[0] = r0 / beta
self.normalize(self.r0, beta_value)
self.copy_vector(self.r0, self.V, 0)
# Step 4: GMRES iteration loop
for j in range(self.n_iter):
temp_vec = ti.field(dtype=ti.f32, shape=(self.rows, self.cols))
self.extract_vector_from_V(j, temp_vec)
# Apply preconditioned matrix-vector product: w = D^{-1} * linear_map(V[j])
linear_map(temp_vec, self.w) # Compute w = linear_map(V[j])
self.apply_preconditioner(self.w, self.w) # Apply Jacobi preconditioner
self.orthogonalize_in_python(j) # Orthogonalize
e1 = ti.field(dtype=ti.f32, shape=(self.n_iter + 1))
e1[0] = self.beta[None]
y = ti.field(dtype=ti.f32, shape=(self.n_iter))
# Apply Givens rotations and solve least squares
self.apply_givens_rotations(e1, y)
# Compute the new x
x_new = ti.field(dtype=ti.f32, shape=(self.rows, self.cols))
for i in range(self.rows):
for j in range(self.cols):
sum_val = 0.0
for k in range(self.n_iter):
sum_val += self.V[k, i, j] * y[k]
x_new[i, j] = x0[i, j] + sum_val
return x_new
Make it run faster
To make your GMRES solver run faster, you can optimize the code by leveraging Taichi's parallel computing capabilities more effectively. Here are some specific suggestions to improve the performance:
Move Python Loops into Taichi Kernels:
Currently, your orthogonalize_in_python function operates in Python scope, which can be a significant performance bottleneck due to the overhead of Python loops and frequent kernel launches. By converting this function into a Taichi kernel, you can parallelize the computations and reduce overhead.
Optimize Givens Rotations:
The apply_givens_rotations function also contains loops that can be optimized. Ensuring that computations inside these loops are executed within Taichi kernels can help utilize parallelism and improve speed.
Minimize Data Transfers Between CPU and GPU:
Reduce the number of times data is transferred between Python (CPU) and Taichi (GPU) scopes. Each transfer can introduce latency, so keeping as much computation within Taichi kernels as possible is beneficial.
Use Taichi's Built-in Functions:
Utilize Taichi's built-in functions for vector operations, norms, and dot products, which are optimized for performance.
Profile the Code:
Use Taichi's profiling tools to identify bottlenecks in your code. This can help you focus optimization efforts where they will have the most impact.
Implementing the Optimizations:
Below is the modified code with the suggested optimizations:
python
import taichi as ti
ti.init(arch=ti.gpu)
@ti.data_oriented
class GMRES_Solver:
def __init__(self, rows, cols, n_iter=1, tol=1e-6):
self.rows = rows
self.cols = cols
self.n_iter = n_iter
self.tol = tol # Convergence tolerance
# Taichi fields for 2D vectors and matrices
self.x0 = ti.field(dtype=ti.f32, shape=(rows, cols))
self.b = ti.field(dtype=ti.f32, shape=(rows, cols))
self.V = ti.field(dtype=ti.f32, shape=(n_iter + 1, rows, cols))
self.H = ti.field(dtype=ti.f32, shape=(n_iter + 1, n_iter))
self.w = ti.field(dtype=ti.f32, shape=(rows, cols))
self.beta = ti.field(dtype=ti.f32, shape=())
self.r0 = ti.field(dtype=ti.f32, shape=(rows, cols))
self.diagonal_inv = ti.field(dtype=ti.f32, shape=(rows, cols))
# Fields for Givens rotations
self.cs = ti.field(dtype=ti.f32, shape=self.n_iter)
self.sn = ti.field(dtype=ti.f32, shape=self.n_iter)
self.s = ti.field(dtype=ti.f32, shape=(self.n_iter + 1))
# Kernel for vector subtraction: result = v1 - v2
@ti.kernel
def subtract_vectors(self, v1: ti.template(), v2: ti.template(), result: ti.template()):
for i, j in ti.ndrange(self.rows, self.cols):
result[i, j] = v1[i, j] - v2[i, j]
# Kernel for vector normalization and computing the norm
@ti.kernel
def normalize_and_compute_norm(self, v: ti.template(), norm: ti.template()):
norm_val = 0.0
for i, j in ti.ndrange(self.rows, self.cols):
norm_val += v[i, j] * v[i, j]
norm[None] = ti.sqrt(norm_val)
for i, j in ti.ndrange(self.rows, self.cols):
v[i, j] /= norm[None]
# Kernel to copy one vector to another
@ti.kernel
def copy_vector(self, src: ti.template(), dst: ti.template(), idx: ti.i32):
for i, j in ti.ndrange(self.rows, self.cols):
dst[idx, i, j] = src[i, j]
# Kernel for dot product
@ti.kernel
def dot_product(self, v1: ti.template(), v2: ti.template()) -> ti.f32:
dot = 0.0
for i, j in ti.ndrange(self.rows, self.cols):
dot += v1[i, j] * v2[i, j]
return dot
# Kernel for in-place subtraction: v1 -= scalar * v2
@ti.kernel
def subtract_scaled_vector(self, v1: ti.template(), v2: ti.template(), scalar: ti.f32):
for i, j in ti.ndrange(self.rows, self.cols):
v1[i, j] -= scalar * v2[i, j]
# Kernel for preconditioned matrix-vector multiplication: result = D^{-1} * v
@ti.kernel
def apply_preconditioner(self, v: ti.template(), result: ti.template()):
for i, j in ti.ndrange(self.rows, self.cols):
result[i, j] = self.diagonal_inv[i, j] * v[i, j] # Applying diagonal inverse
# Taichi kernel for orthogonalization
@ti.kernel
def orthogonalize(self, j: ti.i32):
for i in range(j + 1):
# Compute H[i, j] = dot_product(w, V[i])
h_ij = 0.0
for m, n in ti.ndrange(self.rows, self.cols):
h_ij += self.w[m, n] * self.V[i, m, n]
self.H[i, j] = h_ij
# w = w - H[i, j] * V[i]
for m, n in ti.ndrange(self.rows, self.cols):
self.w[m, n] -= h_ij * self.V[i, m, n]
# H[j + 1, j] = norm(w)
norm_w = 0.0
for m, n in ti.ndrange(self.rows, self.cols):
norm_w += self.w[m, n] ** 2
norm_w = ti.sqrt(norm_w)
self.H[j + 1, j] = norm_w
# V[j + 1] = w / H[j + 1, j]
for m, n in ti.ndrange(self.rows, self.cols):
self.V[j + 1, m, n] = self.w[m, n] / norm_w
# Updated function for applying Givens rotations
@ti.kernel
def apply_givens_rotations(self, j: ti.i32):
# Apply Givens rotations to H and s
for i in range(j):
temp = self.cs[i] * self.H[i, j] + self.sn[i] * self.H[i + 1, j]
self.H[i + 1, j] = -self.sn[i] * self.H[i, j] + self.cs[i] * self.H[i + 1, j]
self.H[i, j] = temp
# Compute the next rotation parameters
delta = ti.sqrt(self.H[j, j] ** 2 + self.H[j + 1, j] ** 2)
self.cs[j] = self.H[j, j] / delta
self.sn[j] = self.H[j + 1, j] / delta
# Eliminate H[j + 1, j]
self.H[j, j] = self.cs[j] * self.H[j, j] + self.sn[j] * self.H[j + 1, j]
self.H[j + 1, j] = 0.0
# Update the residual vector s
temp = self.cs[j] * self.s[j] + self.sn[j] * self.s[j + 1]
self.s[j + 1] = -self.sn[j] * self.s[j] + self.cs[j] * self.s[j + 1]
self.s[j] = temp
# Kernel for back substitution to solve the upper triangular system
@ti.kernel
def back_substitution(self, y: ti.template(), n_iter: ti.i32):
for i in range(n_iter - 1, -1, -1):
sum_val = 0.0
for j in range(i + 1, n_iter):
sum_val += self.H[i, j] * y[j]
y[i] = (self.s[i] - sum_val) / self.H[i, i]
# Kernel to update the solution x_new
@ti.kernel
def update_solution(self, x0: ti.template(), y: ti.template(), x_new: ti.template(), n_iter: ti.i32):
for i, j in ti.ndrange(self.rows, self.cols):
sum_val = 0.0
for k in range(n_iter):
sum_val += self.V[k, i, j] * y[k]
x_new[i, j] = x0[i, j] + sum_val
# GMRES solver function with Jacobi preconditioner
def gmres_solve(self, b, x0, linear_map, diagonal):
# Set up the preconditioner (diagonal inverse)
@ti.kernel
def setup_diagonal_inv():
for i, j in ti.ndrange(self.rows, self.cols):
if diagonal[i, j] != 0:
self.diagonal_inv[i, j] = 1.0 / diagonal[i, j]
else:
self.diagonal_inv[i, j] = 0.0 # Handle zeros in the diagonal
setup_diagonal_inv()
# Step 1: r0 = b - linear_map(x0)
linear_map(x0, self.r0)
self.subtract_vectors(b, self.r0, self.r0)
# Apply Jacobi preconditioner to r0: r0 = D^{-1} * r0
self.apply_preconditioner(self.r0, self.r0)
# Step 2: beta = norm(r0)
beta = ti.field(dtype=ti.f32, shape=())
self.normalize_and_compute_norm(self.r0, beta)
self.beta[None] = beta[None]
# Step 3: V[0] = r0
self.copy_vector(self.r0, self.V, 0)
# Initialize s vector
self.s.fill(0)
self.s[0] = self.beta[None]
# GMRES iteration loop
for j in range(self.n_iter):
# w = linear_map(V[j])
@ti.kernel
def compute_w():
for i, k in ti.ndrange(self.rows, self.cols):
self.w[i, k] = 0.0 # Initialize w to zero
compute_w()
def linear_map_Vj(Vj, w):
linear_map(Vj, w)
Vj = self.V[j]
linear_map_Vj(Vj, self.w)
# Apply preconditioner to w
self.apply_preconditioner(self.w, self.w)
# Orthogonalization process
self.orthogonalize(j)
# Apply Givens rotations
self.apply_givens_rotations(j)
# Check for convergence
resid = abs(self.s[j + 1]) / self.beta[None]
if resid < self.tol:
self.n_iter = j + 1
break
# Solve the upper triangular system
y = ti.field(dtype=ti.f32, shape=(self.n_iter))
self.back_substitution(y, self.n_iter)
# Update the solution x_new
x_new = ti.field(dtype=ti.f32, shape=(self.rows, self.cols))
self.update_solution(x0, y, x_new, self.n_iter)
return x_new
Explanation of Optimizations:
Converted orthogonalize_in_python to a Taichi Kernel:
The orthogonalize function now operates entirely within a Taichi kernel, allowing the loops and computations to be parallelized. This significantly reduces overhead from Python loops and function calls.
Optimized Givens Rotations:
The apply_givens_rotations function has been adjusted to ensure that computations are performed efficiently within a Taichi kernel. By operating on Taichi fields and minimizing Python scope computations, we improve performance.
Reduced Data Transfers:
By keeping computations within Taichi kernels and operating on Taichi fields, we minimize the amount of data transferred between the CPU and GPU.
Utilized Taichi's Parallelism:
All heavy computations, especially those involving loops over data indices, have been moved into Taichi kernels. This allows the computations to be executed in parallel, leveraging the full power of the GPU.
Consolidated Kernels Where Appropriate:
In some cases, separate small kernels were combined or restructured to reduce the number of kernel launches and improve data locality.
Handled Potential Divide-by-Zero in Preconditioner:
The preconditioner setup now includes a check to prevent division by zero when inverting the diagonal elements.
Additional Suggestions:
Profile Your Code:
Use Taichi's profiling tools to identify any remaining bottlenecks. This can help you focus further optimization efforts on specific parts of the code.
Optimize linear_map Function:
Ensure that the linear_map function is optimized and, if possible, operates within Taichi kernels. If it includes operations that can benefit from parallelism, implementing it with Taichi can greatly improve performance.
Adjust Data Types if Necessary:
While ti.f32 is generally good for performance, consider using ti.f64 if you require higher precision and the performance impact is acceptable.
Test for Correctness After Optimization:
After making these changes, thoroughly test your solver to ensure that it still produces correct results. Numerical methods can be sensitive to implementation details, so validation is important.
Conclusion:
By moving computations into Taichi kernels and optimizing the loops and operations, you should see a significant improvement in the performance of your GMRES solver. Leveraging Taichi's capabilities allows you to execute computations in parallel, making full use of your hardware's potential.
Feel free to adjust the code according to your specific needs and to extend the optimizations further based on profiling results and testing.