Skip to content

Commit

Permalink
blas: add initial OpenBLAS exploration code
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Bevenius <[email protected]>
  • Loading branch information
danbev committed May 19, 2024
1 parent 0581a7a commit 829835b
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 0 deletions.
1 change: 1 addition & 0 deletions fundamentals/blas/openblas/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bin
20 changes: 20 additions & 0 deletions fundamentals/blas/openblas/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
CC = gcc
SRCDIR = src
BINDIR = bin

SOURCES := $(wildcard $(SRCDIR)/*.c)
TARGETS := $(patsubst $(SRCDIR)/%.c, %, $(SOURCES))

all: $(TARGETS)

$(TARGETS): % : $(SRCDIR)/%.c | bindir
$(CC) -o ${BINDIR}/$@ $< -lopenblas

bindir: bin

bin:
@mkdir -p $(BINDIR)

.PHONY: clean
clean:
@${RM} -rf $(BINDIR)
15 changes: 15 additions & 0 deletions fundamentals/blas/openblas/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
## OpenBLAS
This is an implementation of BLAS for CPUs.


### Installation
```console
$ sudo apt update
$ sudo apt install libopenblas-dev
```

### Building
```console
$ make vector_add
```

43 changes: 43 additions & 0 deletions fundamentals/blas/openblas/src/gemm.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <stdio.h>
#include <cblas.h>

int main() {
const int M = 2; // Number of rows of matrix A and C
const int N = 2; // Number of columns of matrix B and C
const int K = 3; // Number of columns of matrix A and rows of matrix B

float alpha = 1.0f;
float beta = 0.0f;

// Declare matrices A, B, and C
float A[M*K];
float B[K*N];
float C[M*N];

// Initialize matrices A and B with given values
A[0] = 1; A[1] = 2; A[2] = 3;
A[3] = 4; A[4] = 5; A[5] = 6;

B[0] = 1; B[1] = 2;
B[2] = 3; B[3] = 4;
B[4] = 5; B[5] = 6;

// Initialize matrix C with initial non-zero values
C[0] = 0; C[1] = 0;
C[2] = 0; C[3] = 0;

// Perform matrix multiplication C = alpha * A * B + beta * C
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, A, K, B, N, beta, C, N);

// Print the resulting matrix C
printf("Resulting matrix C:\n");
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
printf("%f ", C[i*N + j]);
}
printf("\n");
}

return 0;
}

20 changes: 20 additions & 0 deletions fundamentals/blas/openblas/src/vector_add.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <cblas.h>
#include <stdio.h>

int main() {
int n = 5;
float x[] = {1, 2, 3, 4, 5};
float y[] = {5, 4, 3, 2, 1};
float alpha = 1.0;

// y = alpha * x + y
cblas_saxpy(n, alpha, x, 1, y, 1);

for (int i = 0; i < n; i++) {
printf("%f ", y[i]);
}
printf("\n");

return 0;
}

0 comments on commit 829835b

Please sign in to comment.