openblas example
- User
openblas example
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
openblas example
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, here's an example of using OpenBLAS with strided matrices. OpenBLAS provides a C interface (CBLAS) that allows you to specify matrix dimensions and leading dimensions (strides) directly.
This example performs the same matrix multiplication using row-major matrices with custom strides.
Key Concepts with OpenBLAS (CBLAS):
CblasRowMajor and CblasColMajor.lda, ldb, ldc):
CblasRowMajor: This is the stride between the start of consecutive rows. It must be >= the number of columns of that matrix.CblasColMajor: This is the stride between the start of consecutive columns. It must be >= the number of rows of that matrix.cblas_ (e.g., cblas_dgemm for double-precision general matrix multiply).#include <cblas.h> // Header for OpenBLAS CBLAS interface
#include <stdio.h>
#include <stdlib.h>
int main() {
// Matrix dimensions
const int M = 2; // Rows of A and C
const int N = 2; // Columns of B and C
const int K = 3; // Columns of A / Rows of B
// Strides (elements between consecutive rows in memory)
const int stride_A = 4; // Matrix A (M x K) has M rows, each row takes stride_A elements
const int stride_B = 5; // Matrix B (K x N) has K rows, each row takes stride_B elements
const int stride_C = 3; // Matrix C (M x N) has M rows, each row takes stride_C elements
// --- Host Data Allocation ---
// Allocate enough memory to hold the matrices according to their strides.
// For row-major, total size = num_rows * stride.
double *h_A = (double*)malloc(M * stride_A * sizeof(double));
double *h_B = (double*)malloc(K * stride_B * sizeof(double));
double *h_C = (double*)malloc(M * stride_C * sizeof(double)); // For the result
if (!h_A || !h_B || !h_C) {
perror("Failed to allocate host memory");
return 1; // Indicate an error
}
// --- Initialize Host Matrices with Strides ---
// Initialize h_A (2x3 matrix, row stride = 4)
// Conceptually:
// [ 1 3 5 pad ]
// [ 2 4 6 pad ]
double temp_A_data[] = {1, 3, 5, 2, 4, 6}; // Contiguous data for A's content
for (int i = 0; i < M; ++i) { // Iterate through rows
for (int j = 0; j < K; ++j) { // Iterate through logical columns
// Place element at correct position considering the row stride
h_A[i * stride_A + j] = temp_A_data[i * K + j];
}
// Optionally fill the padding space with zeros
for (int j = K; j < stride_A; ++j) {
h_A[i * stride_A + j] = 0.0;
}
}
// Initialize h_B (3x2 matrix, row stride = 5)
// Conceptually:
// [ 7 10 pad pad pad ]
// [ 8 11 pad pad pad ]
// [ 9 12 pad pad pad ]
double temp_B_data[] = {7, 10, 8, 11, 9, 12}; // Contiguous data for B's content
for (int i = 0; i < K; ++i) { // Iterate through rows
for (int j = 0; j < N; ++j) { // Iterate through logical columns
// Place element at correct position considering the row stride
h_B[i * stride_B + j] = temp_B_data[i * N + j];
}
// Optionally fill the padding space with zeros
for (int j = N; j < stride_B; ++j) {
h_B[i * stride_B + j] = 0.0;
}
}
// Initialize h_C (2x2 matrix, row stride = 3) to zero
// Conceptually:
// [ 0 0 pad ]
// [ 0 0 pad ]
for (int i = 0; i < M; ++i) { // Iterate through rows
for (int j = 0; j < N; ++j) { // Iterate through logical columns
h_C[i * stride_C + j] = 0.0;
}
// Optionally fill padding
for (int j = N; j < stride_C; ++j) {
h_C[i * stride_C + j] = 0.0;
}
}
// --- Perform Matrix Multiplication using OpenBLAS ---
// C = alpha * A * B + beta * C
const double alpha = 1.0; // Scalar for A*B
const double beta = 0.0; // Scalar for C (0 means C is overwritten)
printf("Performing C = A * B (row-major strided) using OpenBLAS\n");
printf("Matrix A (%dx%d), stride_A=%d\n", M, K, stride_A);
printf("Matrix B (%dx%d), stride_B=%d\n", K, N, stride_B);
printf("Matrix C (%dx%d), stride_C=%d\n", M, N, stride_C);
// Call the CBLAS dgemm function
cblas_dgemm(
CblasRowMajor, // Storage order: CblasRowMajor or CblasColMajor
CblasNoTrans, // Transpose option for matrix A
CblasNoTrans, // Transpose option for matrix B
M, // Number of rows of matrix A (and C)
N, // Number of columns of matrix B (and C)
K, // Number of columns of A / Number of rows of B
alpha, // Scalar multiplier for the product A*B
h_A, // Pointer to matrix A
stride_A, // Leading dimension (row stride) of matrix A
h_B, // Pointer to matrix B
stride_B, // Leading dimension (row stride) of matrix B
beta, // Scalar multiplier for matrix C
h_C, // Pointer to matrix C (result)
stride_C // Leading dimension (row stride) of matrix C
);
// --- Print the Result Matrix C ---
printf("\nResult Matrix C:\n");
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
// Access elements using the row stride
printf("%6.1f ", h_C[i * stride_C + j]);
}
printf("\n");
}
// --- Clean Up ---
free(h_A);
free(h_B);
free(h_C);
return 0; // Success
}
Install OpenBLAS: Make sure you have OpenBLAS installed on your system. This often involves installing a package like libopenblas-dev (on Debian/Ubuntu) or downloading and compiling it.
Compile: You need to tell the compiler where to find the OpenBLAS headers (-I) and library (-L), and then link against the OpenBLAS library (-lopenblas).
# Example for GCC on Linux, assuming OpenBLAS is installed system-wide
gcc openblas_strided_example.c -lopenblas -o openblas_example
# If OpenBLAS is installed in a custom location (e.g., /opt/OpenBLAS):
# gcc openblas_strided_example.c -I/opt/OpenBLAS/include -L/opt/OpenBLAS/lib -lopenblas -o openblas_example
Run:
./openblas_example
Performing C = A * B (row-major strided) using OpenBLAS
Matrix A (2x3), stride_A=4
Matrix B (3x2), stride_B=5
Matrix C (2x2), stride_C=3
Result Matrix C:
76.0 103.0
100.0 136.0
This output matches the expected result from the previous BLAS and cuBLAS examples, demonstrating how OpenBLAS correctly handles matrices with custom strides.
blas vs blis
Okay, let's break down the relationship and differences between BLAS and BLIS.
Think of it this way:
Here's a more detailed comparison:
axpy).gemv).gemm). Level 3 operations are the most computationally intensive and offer the most potential for optimization.give an example of using blis
Okay, here's an example using the BLIS (BLAS-like Infrastructure for Scalable High-performance linear algebra) library. BLIS is designed for high performance on modern CPUs, utilizing techniques like micro-kernels, data packing, and advanced vectorization.
This example performs matrix multiplication using row-major matrices with custom strides, similar to the previous examples.
Prerequisites:
gemm), by leveraging advanced techniques. It focuses on performance portability – achieving high performance across a wide range of hardware (different CPUs, instruction sets like AVX, AVX2, AVX-512, ARM NEON).bli_... functions) which exposes more fine-grained control over packing, blocking, and other tuning parameters, but this is less portable.| Feature | BLAS (Specification) | BLIS (Framework/Implementation) |
|---|---|---|
| Nature | Standardized API/Specification | High-performance implementation & framework |
| Primary Goal | Define common linear algebra operations | Achieve peak performance, especially on modern CPUs |
| Focus | Portability of the interface | Performance portability across architectures & instruction sets |
| Performance | Varies greatly depending on the implementation used | Generally state-of-the-art, highly optimized |
| Key Techniques | Varies by implementation (basic to optimized) | Micro-kernels, data packing, loop tiling, SIMD, multi-threading |
| API | Defines the standard interface | Implements the standard BLAS API (+ its own extended API) |
| Extensibility | Limited (standard is fixed) | High (designed for adding new kernels/features) |
| Examples | Netlib BLAS, OpenBLAS, MKL, ATLAS, cuBLAS | The BLIS library itself |
In essence: If you write code using the BLAS API, you are using the BLAS specification. The actual performance you get depends on which BLAS implementation (like OpenBLAS or MKL) your code links against. BLIS is a specific, advanced way to build a BLAS implementation that prioritizes cutting-edge performance through sophisticated internal techniques.
#include <stdio.h>
#include <stdlib.h>
#include <blis.h> // Include the BLIS header
int main() {
// --- Configuration ---
// Matrix dimensions
const dim_t M = 2; // Rows of A and C
const dim_t N = 2; // Columns of B and C
const dim_t K = 3; // Columns of A / Rows of B
// Strides (elements between consecutive rows for row-major storage)
const dim_t rA = 4; // Row stride for matrix A
const dim_t rB = 5; // Row stride for matrix B
const dim_t rC = 3; // Row stride for matrix C
// Column strides (for row-major, elements within a row are contiguous)
const dim_t cA = 1;
const dim_t cB = 1;
const dim_t cC = 1;
// BLIS operation parameters
const int transa = BLIS_NO_TRANS; // No transpose for A
const int transb = BLIS_NO_TRANS; // No transpose for B
const double alpha = 1.0; // Scalar multiplier for A*B
const double beta = 0.0; // Scalar multiplier for C (0 means C is overwritten)
// --- BLIS Initialization ---
// Initialize BLIS. `bli_init_auto()` attempts to detect the best configuration.
// You can also use `bli_init()` for default settings or specific configurations.
if (bli_init_auto() != BLIS_SUCCESS) {
fprintf(stderr, "Error: Failed to initialize BLIS.\n");
return 1;
}
// --- Host Data Allocation ---
// Allocate memory for matrices A, B, and C respecting the strides.
// For row-major, total size = num_rows * row_stride.
double *h_A = (double*)malloc(M * rA * sizeof(double));
double *h_B = (double*)malloc(K * rB * sizeof(double));
double *h_C = (double*)malloc(M * rC * sizeof(double)); // Result matrix
if (!h_A || !h_B || !h_C) {
fprintf(stderr, "Error: Failed to allocate host memory.\n");
// Clean up any allocated memory before exiting
free(h_A); free(h_B); free(h_C);
bli_finalize(); // Always finalize BLIS
return 1;
}
// --- Initialize Host Matrices ---
// Initialize h_A (2x3, row stride 4)
// Data: [ 1 3 5 pad ]
// [ 2 4 6 pad ]
double temp_A_data[] = {1, 3, 5, 2, 4, 6};
for (dim_t i = 0; i < M; ++i) {
for (dim_t j = 0; j < K; ++j) {
h_A[i * rA + j] = temp_A_data[i * K + j];
}
// Fill padding with zeros (optional, but good practice)
for (dim_t j = K; j < rA; ++j) {
h_A[i * rA + j] = 0.0;
}
}
// Initialize h_B (3x2, row stride 5)
// Data: [ 7 10 pad pad pad ]
// [ 8 11 pad pad pad ]
// [ 9 12 pad pad pad ]
double temp_B_data[] = {7, 10, 8, 11, 9, 12};
for (dim_t i = 0; i < K; ++i) {
for (dim_t j = 0; j < N; ++j) {
h_B[i * rB + j] = temp_B_data[i * N + j];
}
// Fill padding
for (dim_t j = N; j < rB; ++j) {
h_B[i * rB + j] = 0.0;
}
}
// Initialize h_C (2x2, row stride 3) to zeros
// Data: [ 0 0 pad ]
// [ 0 0 pad ]
for (dim_t i = 0; i < M; ++i) {
for (dim_t j = 0; j < N; ++j) {
h_C[i * rC + j] = 0.0;
}
// Fill padding
for (dim_t j = N; j < rC; ++j) {
h_C[i * rC + j] = 0.0;
}
}
// --- Perform Matrix Multiplication using BLIS ---
printf("Performing C = A * B (row-major strided) using BLIS\n");
printf("Matrix A (%lud x %lud), row_stride=%lud, col_stride=%lud\n", M, K, rA, cA);
printf("Matrix B (%lud x %lud), row_stride=%lud, col_stride=%lud\n", K, N, rB, cB);
printf("Matrix C (%lud x %lud), row_stride=%lud, col_stride=%lud\n", M, N, rC, cC);
// Call the BLIS dgemm function for double-precision general matrix multiplication
bli_dgemm(
transa, // Transpose option for A (BLIS_NO_TRANS, BLIS_TRANS, BLIS_CONJ_TRANS)
transb, // Transpose option for B
M, // Number of rows of A / C
N, // Number of columns of B / C
K, // Inner dimension (columns of A, rows of B)
alpha, // Scalar multiplier for A*B
h_A, // Pointer to matrix A data
rA, // Row stride of A
cA, // Column stride of A
h_B, // Pointer to matrix B data
rB, // Row stride of B
cB, // Column stride of B
beta, // Scalar multiplier for C
h_C, // Pointer to matrix C (result)
rC, // Row stride of C
cC // Column stride of C
);
// --- Print the Result Matrix C ---
printf("\nResult Matrix C:\n");
for (dim_t i = 0; i < M; ++i) {
for (dim_t j = 0; j < N; ++j) {
// Access elements using the row stride
printf("%6.1f ", h_C[i * rC + j]);
}
printf("\n");
}
// --- Cleanup ---
free(h_A);
free(h_B);
free(h_C);
bli_finalize(); // Finalize BLIS environment
return 0; // Success
}
Install BLIS: If you haven't already, download BLIS source, configure it (e.g., configure --prefix=/path/to/install --enable-shared --enable-openmp might be useful flags), build (make), and install (make install).
Compile: Use gcc (or another C compiler) and link against BLIS.
# Example assuming BLIS is installed in /usr/local and uses system math library
# Make sure to adjust paths if you installed BLIS elsewhere
gcc your_blis_example.c -I/usr/local/include/blis -L/usr/local/lib -lblis -lm -o blis_example
# If BLIS was built with OpenMP support and you want to enable it
# gcc your_blis_example.c -I/usr/local/include/blis -L/usr/local/lib -lblis -lm -fopenmp -o blis_example
-I/usr/local/include/blis: Tells the compiler where to find blis.h. Adjust if your BLIS header is elsewhere.-L/usr/local/lib: Tells the linker where to find the BLIS library file (e.g., libblis.so or libblis.a). Adjust if needed.-lblis: Links against the BLIS library.-lm: Links against the math library (often needed for malloc, printf, etc.).-fopenmp: Link with OpenMP support if BLIS was built with it and you want multi-threading.Run:
./blis_example
Performing C = A * B (row-major strided) using BLIS
Matrix A (2 x 3), row_stride=4, col_stride=1
Matrix B (3 x 2), row_stride=5, col_stride=1
Matrix C (2 x 2), row_stride=3, col_stride=1
Result Matrix C:
76.0 103.0
100.0 136.0
This example shows how to use BLIS directly with C-style arrays and manage strides explicitly, similar to the CBLAS interface. BLIS's internal mechanisms will optimize the execution based on the provided parameters and the underlying CPU architecture.