mirror of
https://github.com/lordmathis/CUDANet.git
synced 2025-11-06 01:34:22 +00:00
Start dense layer implementation
This commit is contained in:
54
src/layers/dense.cpp
Normal file
54
src/layers/dense.cpp
Normal file
@@ -0,0 +1,54 @@
|
||||
#include "dense.h"
|
||||
#include <cublas_v2.h>
|
||||
|
||||
|
||||
Layers::Dense::Dense(int inputSize, int outputSize, cublasHandle_t cublasHandle)
|
||||
: inputSize(inputSize), outputSize(outputSize), cublasHandle(cublasHandle) {
|
||||
|
||||
// Allocate memory for weights and biases
|
||||
weights.resize(inputSize * outputSize);
|
||||
biases.resize(outputSize);
|
||||
|
||||
// Initialize weights and biases (you may customize this part)
|
||||
initializeWeights();
|
||||
initializeBiases();
|
||||
|
||||
// Allocate GPU memory for weights and biases
|
||||
cudaMalloc((void**)&d_weights, sizeof(float) * weights.size());
|
||||
cudaMalloc((void**)&d_biases, sizeof(float) * biases.size());
|
||||
|
||||
// Copy weights and biases to GPU
|
||||
cudaMemcpy(d_weights, weights.data(), sizeof(float) * weights.size(), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_biases, biases.data(), sizeof(float) * biases.size(), cudaMemcpyHostToDevice);
|
||||
}
|
||||
|
||||
Layers::Dense::~Dense() {
|
||||
// Free GPU memory
|
||||
cudaFree(d_weights);
|
||||
cudaFree(d_biases);
|
||||
}
|
||||
|
||||
void Layers::Dense::initializeWeights() {
|
||||
|
||||
float range = sqrt((float) 6/(inputSize + outputSize));
|
||||
|
||||
for (float& weight : weights) {
|
||||
weight = static_cast<float>(rand()) / RAND_MAX * 2.0 * range - range;
|
||||
}
|
||||
}
|
||||
|
||||
void Layers::Dense::initializeBiases() {
|
||||
for (float& bias : biases) {
|
||||
bias = static_cast<float>(rand()) / RAND_MAX * 2.0f - 1.0f;
|
||||
}
|
||||
}
|
||||
|
||||
void Layers::Dense::forward(const float* input, float* output) {
|
||||
// Perform matrix multiplication: output = weights * input + biases
|
||||
const float alpha = 1.0f;
|
||||
const float beta = 1.0f;
|
||||
cublasSgemv(cublasHandle, CUBLAS_OP_N, inputSize, outputSize, &alpha, d_weights, inputSize, input, 1, &beta, output, 1);
|
||||
|
||||
// Add biases
|
||||
cublasSaxpy(cublasHandle, outputSize, &alpha, d_biases, 1, output, 1);
|
||||
}
|
||||
@@ -2,18 +2,6 @@
|
||||
#include <cstdlib>
|
||||
#include "cuda_helper.h"
|
||||
|
||||
// CUDA error checking macro
|
||||
#define CUDA_CHECK(call) \
|
||||
do { \
|
||||
cudaError_t result = call; \
|
||||
if (result != cudaSuccess) { \
|
||||
std::fprintf(stderr, "CUDA error at %s:%d code=%d(%s) \"%s\" \n", \
|
||||
__FILE__, __LINE__, static_cast<unsigned int>(result), \
|
||||
cudaGetErrorString(result), #call); \
|
||||
std::exit(EXIT_FAILURE); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// Initialize CUDA and return the device properties
|
||||
cudaDeviceProp initializeCUDA() {
|
||||
int deviceCount;
|
||||
|
||||
Reference in New Issue
Block a user