import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from numba import cuda, float32
import math
Part 1: CPU-side Setup (Data Preparation and Basic Function Definitions)
Load the dataset
data = pd.read_excel('/content/drive/MyDrive/Data.ods', sheet_name=None)
full_data = pd.concat(data.values())
Preprocess the data
X = full_data.iloc[:, :-1].values
y = full_data.iloc[:, -1].values
Part 2: GPU-accelerated Computation Logic with Numba CUDA
CUDA Kernel for Forward Propagation
@cuda.jit
def forward_propagation_cuda(X, W1, b1, W2, b2, A1, A2):
row = cuda.grid(1)
if row < X.shape[0]:
for j in range(W1.shape[1]):
Z1_val = 0.0
for k in range(W1.shape[0]):
Z1_val += X[row, k] * W1[k, j]
A1[row, j] = math.tanh(Z1_val + b1[j])
code
for j in range(W2.shape[1]):
Z2_val = 0.0
for k in range(W2.shape[0]):
Z2_val += A1[row, k] * W2[k, j]
A2[row, j] = 1 / (1 + math.exp(-(Z2_val + b2[j])))
CUDA Kernel for Backward Propagation
@cuda.jit
def backward_propagation_cuda(X, Y, W1, W2, A1, A2, dW1, dW2, db1, db2, learning_rate):
row = cuda.grid(1)
if row < X.shape[0]:
# Initialize dZ1 array with zeros
dZ1_size = W1.shape[1] # Calculate the size based on the dimensions of W1
dZ1 = cuda.local.array(shape=W1.shape[1], dtype=float32)
for j in range(dZ1_size):
dZ1[j] = 0.0
ValueError: operands could not be broadcast together with shapes (34444,) (8611,)
Please fix quick, I have deadline
Assistant
# Calculate gradients for W2 and b2
dZ2 = A2[row, 0] - Y[row]
for j in range(W2.shape[1]):
db2[j] += dZ2
for k in range(W2.shape[0]):
dW2[k, j] += A1[row, k] * dZ2
# Backpropagate through hidden layer
for j in range(W1.shape[1]):
for k in range(W2.shape[0]):
dZ1[j] += dZ2 * W2[k, j]
# Update gradients for W1 and b1
for j in range(W1.shape[1]):
db1[j] += dZ1[j] * (1 - A1[row, j]**2)
for k in range(W1.shape[0]):
dW1[k, j] += X[row, k] * dZ1[j]
for epoch in range(num_epochs):
# Forward Propagation on Training Data
execute_forward_propagation(X_train_device, W1_device, b1_device, W2_device, b2_device, A1_device, A2_device)
code
# Backward Propagation and Parameter Update
blockspergrid = (X_train.shape[0] + (threadsperblock - 1)) // threadsperblock
backward_propagation_cuda[blockspergrid, threadsperblock](X_train_device, y_train_device, W1_device, W2_device, A1_device, A2_device, dW1_device, dW2_device, db1_device, db2_device, learning_rate)
cuda.synchronize()
# Validation
execute_forward_propagation(X_val_device, W1_device, b1_device, W2_device, b2_device, A1_device, A2_device)
# Calculate and Log Validation Loss
if epoch % 10 == 0:
A2_val = A2_device.copy_to_host()
val_loss = np.mean((A2_val.flatten() - y_val) ** 2)
val_losses.append(val_loss)
print(f"Epoch {epoch}: Validation Loss = {val_loss}")
# Compute Training Loss for Monitoring
train_loss = np.mean((A2_device.copy_to_host().flatten() - y_train) ** 2)
train_losses.append(train_loss)
print(f"Epoch {epoch}: Training Loss = {train_loss}")
Optionally, you can perform inference or further analysis using the trained parameters
Your code is mostly correct, but there are several potential issues and areas for improvement that I'd like to address. I cannot guarantee it will fix your problem without knowledge of the specific errors or undesired behaviors you're encountering, but I can offer some general advice and fixes that could help improve or debug your neural network implementation with Numba and CUDA.
Data Loading with Pandas: The way you concatenate data from an Excel file with multiple sheets appears correct. Ensure the data format in each sheet is consistent.
Data Preprocessing: Your preprocessing steps for normalization and train-test split are fine. Just make sure the target variable y needs to be normalized depending on the problem type (regression vs. classification).
Mismatch or Inadequate Use of math in CUDA Kernels: When working inside CUDA kernels, instead of using the Python math module, use functions from the numba.cuda module for mathematic operations. This is because math module functions may not be supported directly within CUDA kernels.
Replace math.tanh with numba.cuda.math.tanh.
Replace math.exp with numba.cuda.math.exp.
However, make a note that Numba’s JIT compiler often automatically recognizes and replaces math operation with their CUDA equivalents. If tanh and exp indeed work as expected, this issue might be a non-issue. Always verify with the official Numba documentation and based on the actual errors you're facing.
Error or Gradient Calculation: In the backward_propagation_cuda function, you perform the parameter update inside the loop iterating over the dataset. Gradients should be accumulated across all samples before performing an update. Alternatively, if you're attempting a form of online (per-sample) update, your current approach may lead to highly unstable training due to extremely frequent updates. Usually, gradients are accumulated, and parameters are updated once per batch or epoch.
Lack of Synchronization After Kernels: While you correctly call cuda.synchronize() after important steps, ensure that it's appropriately used when needed after kernel launches to ensure correct ordering of operations, especially if you're reading back results to the CPU for loss calculation or debugging purposes.
Loss Computation and Parameter Update: Your method for backpropagation and parameter update doesn't directly reflect the changes back to the original weight matrices W1_device, W2_device, etc., since gradients are stored in separate arrays (dW1_device, dW2_device, etc.). Consider how you intend to update the actual weight matrices using these gradients. An explicit update step seems to be missing in your code where you should adjust W1_device, W2_device, etc., based on the calculated gradients. This step is crucial for the learning process.
Since your code sample does not directly modify the weights using the calculated gradients, you should include an update step, typically:
This step must occur within the loop, after backpropagation, for each epoch. Of course, you need to adapt it to the correct Numba and CUDA paradigms, potentially launching another kernel to handle the update, or manually implementing it inside the backward_propagation_cuda if you intend to simplify.
Remember, debugging neural networks, especially with the addition of GPU acceleration, can be quite challenging due to the asynchronous nature of GPU operations and the difficulty in tracking down numerical issues. Consider simplifying your network and verifying its correctness incrementally, starting with CPU-only implementations, before fully transitioning to CUDA-accelerated versions.
TypingError: Failed in cuda mode pipeline (step: nopython frontend)
No implementation of function Function(<function local.array at 0x7a8131e54430>) found for signature:
array(shape=int64, dtype=class(float32))
There are 2 candidate implementations:
- Of which 2 did not match due to:
Overload of function 'array': File: numba/cuda/cudadecl.py: Line 26.
With argument(s): '(shape=int64, dtype=class(float32))':
No match.
During: resolving callee type: Function(<function local.array at 0x7a8131e54430>)
During: typing of call at (63)
File "", line 63:
def backward_propagation_cuda(X, Y, W1, W2, A1, A2, dW1, dW2, db1, db2, learning_rate):
dZ1_size = W1.shape[1] # Calculate the size based on the dimensions of W1
dZ1 = cuda.local.array(shape=W1.shape[1], dtype=float32)
The error you are encountering, TypingError, stems from an incorrect usage of cuda.local.array in your backward_propagation_cuda CUDA kernel function. Specifically, cuda.local.array expects the shape argument to be a compile-time constant, but you're passing it a value (W1.shape[1]) that is determined at runtime. Numba's compiler needs to know array sizes ahead of time to allocate them on the stack correctly.
Solution
There are a couple of ways to resolve this issue:
Use Static Array Sizes: If it's feasible (knowing the maximum size beforehand), define the shape argument with a constant value. This approach isn't flexible but works if your architectures have fixed sizes.
Pass the Shape as a Kernel Parameter: If the array sizes can vary, consider calculating the necessary size outside the kernel and passing it as an additional argument.
However, for your specific use case where you are trying to dynamically allocate a local array based on the shape of W1, you might consider a workaround since you cannot directly use runtime values for sizing local.array.
Given that dZ1 is an intermediate array used for storing gradients, and you know the maximum possible size in advance (based on your ANN architecture), one approach could be to define a maximum possible size for dZ1. If the architecture of your neural network changes and requires a higher size, you could adjust the constant accordingly.
Example Modified Kernel with Fixed Size:
Consider this modification where I use a constant size for the shape parameter. You need to replace MAX_HIDDEN_SIZE with an appropriate constant value based on your use case:
python
from numba import cuda, float32
@cuda.jit
def backward_propagation_cuda(X, Y, W1, W2, A1, A2, dW1, dW2, db1, db2, learning_rate):
row = cuda.grid(1)
if row < X.shape[0]:
MAX_HIDDEN_SIZE = 10 # Adjust based on your network's maximum expected size
dZ1 = cuda.local.array(shape=(MAX_HIDDEN_SIZE,), dtype=float32)
for j in range(W1.shape[1]): # Proceed as usual...
# Your existing logic here
Note: Adjust MAX_HIDDEN_SIZE to the maximum number of hidden units you expect to have in your network. This is a tradeoff between flexibility and resource utilization; using a very high value might lead to unnecessary memory allocation, while too low a value may not accommodate larger networks.
For longer-term and more flexible solutions, especially if the sizes of your arrays are subject to change, consider designing your kernels with maximum sizes in mind or splitting your problem into smaller fixed-size chunks that can be processed by the kernels. Always ensure your approach aligns with the best practices for GPU memory utilization and computational efficiency.
The ValueError you're encountering is due to a shape mismatch between A2_val.flatten() and y_val. This happens when you try to perform an element-wise subtraction between two arrays of different sizes in NumPy. Your arrays A2_val.flatten() and y_val must have the same number of elements to perform element-wise operations.
Given the shape information in the error message ((34444,) and (8611,)), it looks like there's a discrepancy in the data you're using for validation. Specifically, A2_val (the predictions from your model) and y_val (the true validation targets) must be of the same length for the operation to be valid.
Quick Fix
To address the issue promptly because of your deadline, ensure that when you're performing validation, you're correctly synchronizing the sizes of the validation inputs and outputs with your model's output. This means:
Validate that the shape of A2_device (which should match A2_val after copy_to_host()) is intended for the amount of input data it was calculated from (X_val). This might involve adjusting how you perform the split or how you feed the data to execute_forward_propagation for validation.
Verify that you're using the correct validation dataset that matches how you've set up your network and the splits. The number of predictions (A2_val.flatten()) should match the number of labels in your validation set (y_val).
Assuming X_val_device was correctly transferred to the GPU and corresponds with y_val, check this part:
Ensure that X_val_device has been properly initialized and refers to your validation inputs. The output you're getting from this operation should have the same number of rows as your y_val dataset. This might involve adjusting the shape of A1_device and A2_device specifically for validation if they were originally allocated with training dataset shapes in mind.
Immediate Steps:
Check Data Splits: Re-examine how you've done your train-validation-test split, ensuring the validation data (X_val, y_val) are correctly partitioned and their lengths are what you expect.
Adjust Arrays for Validation: If A1_device and A2_device were initially set up for training data size, you might need separate arrays for validation to match the validation dataset sizes, especially A2_device for storing validation predictions.
Debugging Output: Before calculating the validation loss, print the shapes of A2_val.flatten() and y_val to confirm they match. If they don't, backtrack to see where the size mismatch originates.
Quick validation of array sizes before calculating loss:
python
print(A2_val.flatten().shape, y_val.shape)
# Ensure that both shapes printed here match
Given the urgency noted in your query, these steps aim to guide you towards identifying the mismatch quickly. Thoroughly verify data preprocessing stages and how arrays are passed to and from GPU devices for computation.