1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include "ggml.h" #include "ggml-alloc.h" #include "ggml-backend.h" #ifdef GGML_USE_CUDA #include "ggml-cuda.h" #endif
#include <stdlib.h> #include <string.h> #include <stdio.h>
int main(void) { const int rows_A = 4, cols_A = 2; float matrix_A[rows_A * cols_A] = { 2, 8, 5, 1, 4, 2, 8, 6 }; const int rows_B = 3, cols_B = 2; float matrix_B[rows_B * cols_B] = { 10, 5, 9, 9, 5, 4 };
ggml_backend_t backend = NULL; #ifdef GGML_USE_CUDA fprintf(stderr, "%s: using CUDA backend\n", __func__); backend = ggml_backend_cuda_init(0); if (!backend) { fprintf(stderr, "%s: ggml_backend_cuda_init() failed\n", __func__); } #endif if (!backend) { backend = ggml_backend_cpu_init(); }
size_t ctx_size = 0; ctx_size += 2 * ggml_tensor_overhead();
struct ggml_init_params params = { ctx_size, NULL, true, }; struct ggml_context * ctx = ggml_init(params);
struct ggml_tensor * tensor_a = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cols_A, rows_A); struct ggml_tensor * tensor_b = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cols_B, rows_B);
ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
ggml_backend_tensor_set(tensor_a, matrix_A, 0, ggml_nbytes(tensor_a)); ggml_backend_tensor_set(tensor_b, matrix_B, 0, ggml_nbytes(tensor_b));
struct ggml_cgraph * gf = NULL; struct ggml_context * ctx_cgraph = NULL; { struct ggml_init_params params0 = { ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead(), NULL, true, }; ctx_cgraph = ggml_init(params0); gf = ggml_new_graph(ctx_cgraph);
struct ggml_tensor * result0 = ggml_mul_mat(ctx_cgraph, tensor_a, tensor_b);
ggml_build_forward_expand(gf, result0); }
ggml_gallocr_t allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend)); ggml_gallocr_alloc_graph(allocr, gf);
int n_threads = 1; if (ggml_backend_is_cpu(backend)) { ggml_backend_cpu_set_n_threads(backend, n_threads); } ggml_backend_graph_compute(backend, gf);
struct ggml_tensor * result = gf->nodes[gf->n_nodes - 1]; float * result_data = malloc(ggml_nbytes(result)); ggml_backend_tensor_get(result, result_data, 0, ggml_nbytes(result)); printf("mul mat (%d x %d) (transposed result):\n[", (int) result->ne[0], (int) result->ne[1]); for (int j = 0; j < result->ne[1]; j++) { if (j > 0) { printf("\n"); }
for (int i = 0; i < result->ne[0]; i++) { printf(" %.2f", result_data[j * result->ne[0] + i]); } } printf(" ]\n"); free(result_data);
ggml_free(ctx_cgraph); ggml_gallocr_free(allocr); ggml_free(ctx); ggml_backend_buffer_free(buffer); ggml_backend_free(backend); return 0; }
|