ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / examples / yolo / yolov3-tiny.cpp
| 1 | #include "ggml.h" |
| 2 | #include "gguf.h" |
| 3 | #include "ggml-alloc.h" |
| 4 | #include "ggml-backend.h" |
| 5 | |
| 6 | #include "yolo-image.h" |
| 7 | |
| 8 | #include <cmath> |
| 9 | #include <cstdio> |
| 10 | #include <cstring> |
| 11 | #include <ctime> |
| 12 | #include <string> |
| 13 | #include <vector> |
| 14 | #include <algorithm> |
| 15 | #include <fstream> |
| 16 | #include <algorithm> |
| 17 | #include <thread> |
| 18 | |
| 19 | #if defined(_MSC_VER) |
| 20 | #pragma warning(disable: 4244 4267) // possible loss of data |
| 21 | #endif |
| 22 | |
| 23 | struct conv2d_layer { |
| 24 | struct ggml_tensor * weights; |
| 25 | struct ggml_tensor * biases; |
| 26 | struct ggml_tensor * scales; |
| 27 | struct ggml_tensor * rolling_mean; |
| 28 | struct ggml_tensor * rolling_variance; |
| 29 | int padding = 1; |
| 30 | bool batch_normalize = true; |
| 31 | bool activate = true; // true for leaky relu, false for linear |
| 32 | }; |
| 33 | |
| 34 | struct yolo_model { |
| 35 | int width = 416; |
| 36 | int height = 416; |
| 37 | std::vector<conv2d_layer> conv2d_layers; |
| 38 | ggml_backend_t backend; |
| 39 | ggml_backend_buffer_t buffer; |
| 40 | struct ggml_context * ctx; |
| 41 | }; |
| 42 | |
| 43 | struct yolo_layer { |
| 44 | int classes = 80; |
| 45 | std::vector<int> mask; |
| 46 | std::vector<float> anchors; |
| 47 | std::vector<float> predictions; |
| 48 | int w; |
| 49 | int h; |
| 50 | |
| 51 | yolo_layer(int classes, const std::vector<int> & mask, const std::vector<float> & anchors, struct ggml_tensor * prev_layer) |
| 52 | : classes(classes), mask(mask), anchors(anchors) |
| 53 | { |
| 54 | w = prev_layer->ne[0]; |
| 55 | h = prev_layer->ne[1]; |
| 56 | predictions.resize(ggml_nbytes(prev_layer)/sizeof(float)); |
| 57 | ggml_backend_tensor_get(prev_layer, predictions.data(), 0, ggml_nbytes(prev_layer)); |
| 58 | } |
| 59 | |
| 60 | int entry_index(int location, int entry) const { |
| 61 | int n = location / (w*h); |
| 62 | int loc = location % (w*h); |
| 63 | return n*w*h*(4+classes+1) + entry*w*h + loc; |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | struct box { |
| 68 | float x, y, w, h; |
| 69 | }; |
| 70 | |
| 71 | struct detection { |
| 72 | box bbox; |
| 73 | std::vector<float> prob; |
| 74 | float objectness; |
| 75 | }; |
| 76 | |
| 77 | static bool load_model(const std::string & fname, yolo_model & model) { |
| 78 | struct ggml_context * tmp_ctx = nullptr; |
| 79 | struct gguf_init_params gguf_params = { |
| 80 | /*.no_alloc =*/ false, |
| 81 | /*.ctx =*/ &tmp_ctx, |
| 82 | }; |
| 83 | gguf_context * gguf_ctx = gguf_init_from_file(fname.c_str(), gguf_params); |
| 84 | if (!gguf_ctx) { |
| 85 | fprintf(stderr, "%s: gguf_init_from_file() failed\n", __func__); |
| 86 | return false; |
| 87 | } |
| 88 | |
| 89 | int num_tensors = gguf_get_n_tensors(gguf_ctx); |
| 90 | struct ggml_init_params params { |
| 91 | /*.mem_size =*/ ggml_tensor_overhead() * num_tensors, |
| 92 | /*.mem_buffer =*/ NULL, |
| 93 | /*.no_alloc =*/ true, |
| 94 | }; |
| 95 | model.ctx = ggml_init(params); |
| 96 | for (int i = 0; i < num_tensors; i++) { |
| 97 | const char * name = gguf_get_tensor_name(gguf_ctx, i); |
| 98 | struct ggml_tensor * src = ggml_get_tensor(tmp_ctx, name); |
| 99 | struct ggml_tensor * dst = ggml_dup_tensor(model.ctx, src); |
| 100 | ggml_set_name(dst, name); |
| 101 | } |
| 102 | model.buffer = ggml_backend_alloc_ctx_tensors(model.ctx, model.backend); |
| 103 | // copy tensors from main memory to backend |
| 104 | for (struct ggml_tensor * cur = ggml_get_first_tensor(model.ctx); cur != NULL; cur = ggml_get_next_tensor(model.ctx, cur)) { |
| 105 | struct ggml_tensor * src = ggml_get_tensor(tmp_ctx, ggml_get_name(cur)); |
| 106 | size_t n_size = ggml_nbytes(src); |
| 107 | ggml_backend_tensor_set(cur, ggml_get_data(src), 0, n_size); |
| 108 | } |
| 109 | gguf_free(gguf_ctx); |
| 110 | ggml_free(tmp_ctx); |
| 111 | |
| 112 | model.width = 416; |
| 113 | model.height = 416; |
| 114 | model.conv2d_layers.resize(13); |
| 115 | model.conv2d_layers[7].padding = 0; |
| 116 | model.conv2d_layers[9].padding = 0; |
| 117 | model.conv2d_layers[9].batch_normalize = false; |
| 118 | model.conv2d_layers[9].activate = false; |
| 119 | model.conv2d_layers[10].padding = 0; |
| 120 | model.conv2d_layers[12].padding = 0; |
| 121 | model.conv2d_layers[12].batch_normalize = false; |
| 122 | model.conv2d_layers[12].activate = false; |
| 123 | for (int i = 0; i < (int)model.conv2d_layers.size(); i++) { |
| 124 | char name[256]; |
| 125 | snprintf(name, sizeof(name), "l%d_weights", i); |
| 126 | model.conv2d_layers[i].weights = ggml_get_tensor(model.ctx, name); |
| 127 | snprintf(name, sizeof(name), "l%d_biases", i); |
| 128 | model.conv2d_layers[i].biases = ggml_get_tensor(model.ctx, name); |
| 129 | if (model.conv2d_layers[i].batch_normalize) { |
| 130 | snprintf(name, sizeof(name), "l%d_scales", i); |
| 131 | model.conv2d_layers[i].scales = ggml_get_tensor(model.ctx, name); |
| 132 | snprintf(name, sizeof(name), "l%d_rolling_mean", i); |
| 133 | model.conv2d_layers[i].rolling_mean = ggml_get_tensor(model.ctx, name); |
| 134 | snprintf(name, sizeof(name), "l%d_rolling_variance", i); |
| 135 | model.conv2d_layers[i].rolling_variance = ggml_get_tensor(model.ctx, name); |
| 136 | } |
| 137 | } |
| 138 | return true; |
| 139 | } |
| 140 | |
| 141 | static bool load_labels(const char * filename, std::vector<std::string> & labels) |
| 142 | { |
| 143 | std::ifstream file_in(filename); |
| 144 | if (!file_in) { |
| 145 | return false; |
| 146 | } |
| 147 | std::string line; |
| 148 | while (std::getline(file_in, line)) { |
| 149 | labels.push_back(line); |
| 150 | } |
| 151 | GGML_ASSERT(labels.size() == 80); |
| 152 | return true; |
| 153 | } |
| 154 | |
| 155 | static bool load_alphabet(std::vector<yolo_image> & alphabet) |
| 156 | { |
| 157 | alphabet.resize(8 * 128); |
| 158 | for (int j = 0; j < 8; j++) { |
| 159 | for (int i = 32; i < 127; i++) { |
| 160 | char fname[256]; |
| 161 | snprintf(fname, sizeof(fname), "data/labels/%d_%d.png", i, j); |
| 162 | if (!load_image(fname, alphabet[j*128 + i])) { |
| 163 | fprintf(stderr, "Cannot load '%s'\n", fname); |
| 164 | return false; |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | return true; |
| 169 | } |
| 170 | |
| 171 | static ggml_tensor * apply_conv2d(ggml_context * ctx, ggml_tensor * input, const conv2d_layer & layer) |
| 172 | { |
| 173 | struct ggml_tensor * result = ggml_conv_2d(ctx, layer.weights, input, 1, 1, layer.padding, layer.padding, 1, 1); |
| 174 | if (layer.batch_normalize) { |
| 175 | result = ggml_sub(ctx, result, ggml_repeat(ctx, layer.rolling_mean, result)); |
| 176 | result = ggml_div(ctx, result, ggml_sqrt(ctx, ggml_repeat(ctx, layer.rolling_variance, result))); |
| 177 | result = ggml_mul(ctx, result, ggml_repeat(ctx, layer.scales, result)); |
| 178 | } |
| 179 | result = ggml_add(ctx, result, ggml_repeat(ctx, layer.biases, result)); |
| 180 | if (layer.activate) { |
| 181 | result = ggml_leaky_relu(ctx, result, 0.1f, true); |
| 182 | } |
| 183 | return result; |
| 184 | } |
| 185 | |
| 186 | static void activate_array(float * x, const int n) |
| 187 | { |
| 188 | // logistic activation |
| 189 | for (int i = 0; i < n; i++) { |
| 190 | x[i] = 1./(1. + exp(-x[i])); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | static void apply_yolo(yolo_layer & layer) |
| 195 | { |
| 196 | int w = layer.w; |
| 197 | int h = layer.h; |
| 198 | int N = layer.mask.size(); |
| 199 | float * data = layer.predictions.data(); |
| 200 | for (int n = 0; n < N; n++) { |
| 201 | int index = layer.entry_index(n*w*h, 0); |
| 202 | activate_array(data + index, 2*w*h); |
| 203 | index = layer.entry_index(n*w*h, 4); |
| 204 | activate_array(data + index, (1+layer.classes)*w*h); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | static box get_yolo_box(const yolo_layer & layer, int n, int index, int i, int j, int lw, int lh, int w, int h, int stride) |
| 209 | { |
| 210 | const float * predictions = layer.predictions.data(); |
| 211 | box b; |
| 212 | b.x = (i + predictions[index + 0*stride]) / lw; |
| 213 | b.y = (j + predictions[index + 1*stride]) / lh; |
| 214 | b.w = exp(predictions[index + 2*stride]) * layer.anchors[2*n] / w; |
| 215 | b.h = exp(predictions[index + 3*stride]) * layer.anchors[2*n+1] / h; |
| 216 | return b; |
| 217 | } |
| 218 | |
| 219 | static void correct_yolo_box(box & b, int im_w, int im_h, int net_w, int net_h) |
| 220 | { |
| 221 | int new_w = 0; |
| 222 | int new_h = 0; |
| 223 | if (((float)net_w/im_w) < ((float)net_h/im_h)) { |
| 224 | new_w = net_w; |
| 225 | new_h = (im_h * net_w)/im_w; |
| 226 | } else { |
| 227 | new_h = net_h; |
| 228 | new_w = (im_w * net_h)/im_h; |
| 229 | } |
| 230 | b.x = (b.x - (net_w - new_w)/2./net_w) / ((float)new_w/net_w); |
| 231 | b.y = (b.y - (net_h - new_h)/2./net_h) / ((float)new_h/net_h); |
| 232 | b.w *= (float)net_w/new_w; |
| 233 | b.h *= (float)net_h/new_h; |
| 234 | } |
| 235 | |
| 236 | static void get_yolo_detections(const yolo_layer & layer, std::vector<detection> & detections, int im_w, int im_h, int netw, int neth, float thresh) |
| 237 | { |
| 238 | int w = layer.w; |
| 239 | int h = layer.h; |
| 240 | int N = layer.mask.size(); |
| 241 | const float * predictions = layer.predictions.data(); |
| 242 | std::vector<detection> result; |
| 243 | for (int i = 0; i < w*h; i++) { |
| 244 | for (int n = 0; n < N; n++) { |
| 245 | int obj_index = layer.entry_index(n*w*h + i, 4); |
| 246 | float objectness = predictions[obj_index]; |
| 247 | if (objectness <= thresh) { |
| 248 | continue; |
| 249 | } |
| 250 | detection det; |
| 251 | int box_index = layer.entry_index(n*w*h + i, 0); |
| 252 | int row = i / w; |
| 253 | int col = i % w; |
| 254 | det.bbox = get_yolo_box(layer, layer.mask[n], box_index, col, row, w, h, netw, neth, w*h); |
| 255 | correct_yolo_box(det.bbox, im_w, im_h, netw, neth); |
| 256 | det.objectness = objectness; |
| 257 | det.prob.resize(layer.classes); |
| 258 | for (int j = 0; j < layer.classes; j++) { |
| 259 | int class_index = layer.entry_index(n*w*h + i, 4 + 1 + j); |
| 260 | float prob = objectness*predictions[class_index]; |
| 261 | det.prob[j] = (prob > thresh) ? prob : 0; |
| 262 | } |
| 263 | detections.push_back(det); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | static float overlap(float x1, float w1, float x2, float w2) |
| 269 | { |
| 270 | float l1 = x1 - w1/2; |
| 271 | float l2 = x2 - w2/2; |
| 272 | float left = l1 > l2 ? l1 : l2; |
| 273 | float r1 = x1 + w1/2; |
| 274 | float r2 = x2 + w2/2; |
| 275 | float right = r1 < r2 ? r1 : r2; |
| 276 | return right - left; |
| 277 | } |
| 278 | |
| 279 | static float box_intersection(const box & a, const box & b) |
| 280 | { |
| 281 | float w = overlap(a.x, a.w, b.x, b.w); |
| 282 | float h = overlap(a.y, a.h, b.y, b.h); |
| 283 | if (w < 0 || h < 0) return 0; |
| 284 | float area = w*h; |
| 285 | return area; |
| 286 | } |
| 287 | |
| 288 | static float box_union(const box & a, const box & b) |
| 289 | { |
| 290 | float i = box_intersection(a, b); |
| 291 | float u = a.w*a.h + b.w*b.h - i; |
| 292 | return u; |
| 293 | } |
| 294 | |
| 295 | static float box_iou(const box & a, const box & b) |
| 296 | { |
| 297 | return box_intersection(a, b)/box_union(a, b); |
| 298 | } |
| 299 | |
| 300 | static void do_nms_sort(std::vector<detection> & dets, int classes, float thresh) |
| 301 | { |
| 302 | int k = (int)dets.size()-1; |
| 303 | for (int i = 0; i <= k; ++i) { |
| 304 | if (dets[i].objectness == 0) { |
| 305 | std::swap(dets[i], dets[k]); |
| 306 | --k; |
| 307 | --i; |
| 308 | } |
| 309 | } |
| 310 | int total = k+1; |
| 311 | for (int k = 0; k < classes; ++k) { |
| 312 | std::sort(dets.begin(), dets.begin()+total, [=](const detection & a, const detection & b) { |
| 313 | return a.prob[k] > b.prob[k]; |
| 314 | }); |
| 315 | for (int i = 0; i < total; ++i) { |
| 316 | if (dets[i].prob[k] == 0) { |
| 317 | continue; |
| 318 | } |
| 319 | box a = dets[i].bbox; |
| 320 | for (int j = i+1; j < total; ++j){ |
| 321 | box b = dets[j].bbox; |
| 322 | if (box_iou(a, b) > thresh) { |
| 323 | dets[j].prob[k] = 0; |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | static float get_color(int c, int x, int max) |
| 331 | { |
| 332 | float colors[6][3] = { {1,0,1}, {0,0,1}, {0,1,1}, {0,1,0}, {1,1,0}, {1,0,0} }; |
| 333 | float ratio = ((float)x/max)*5; |
| 334 | int i = floor(ratio); |
| 335 | int j = ceil(ratio); |
| 336 | ratio -= i; |
| 337 | float r = (1-ratio) * colors[i][c] + ratio*colors[j][c]; |
| 338 | return r; |
| 339 | } |
| 340 | |
| 341 | static void draw_detections(yolo_image & im, const std::vector<detection> & dets, float thresh, const std::vector<std::string> & labels, const std::vector<yolo_image> & alphabet) |
| 342 | { |
| 343 | int classes = (int)labels.size(); |
| 344 | for (int i = 0; i < (int)dets.size(); i++) { |
| 345 | std::string labelstr; |
| 346 | int cl = -1; |
| 347 | for (int j = 0; j < (int)dets[i].prob.size(); j++) { |
| 348 | if (dets[i].prob[j] > thresh) { |
| 349 | if (cl < 0) { |
| 350 | labelstr = labels[j]; |
| 351 | cl = j; |
| 352 | } else { |
| 353 | labelstr += ", "; |
| 354 | labelstr += labels[j]; |
| 355 | } |
| 356 | printf("%s: %.0f%%\n", labels[j].c_str(), dets[i].prob[j]*100); |
| 357 | } |
| 358 | } |
| 359 | if (cl >= 0) { |
| 360 | int width = im.h * .006; |
| 361 | int offset = cl*123457 % classes; |
| 362 | float red = get_color(2,offset,classes); |
| 363 | float green = get_color(1,offset,classes); |
| 364 | float blue = get_color(0,offset,classes); |
| 365 | float rgb[3]; |
| 366 | |
| 367 | rgb[0] = red; |
| 368 | rgb[1] = green; |
| 369 | rgb[2] = blue; |
| 370 | box b = dets[i].bbox; |
| 371 | |
| 372 | int left = (b.x-b.w/2.)*im.w; |
| 373 | int right = (b.x+b.w/2.)*im.w; |
| 374 | int top = (b.y-b.h/2.)*im.h; |
| 375 | int bot = (b.y+b.h/2.)*im.h; |
| 376 | |
| 377 | if (left < 0) left = 0; |
| 378 | if (right > im.w-1) right = im.w-1; |
| 379 | if (top < 0) top = 0; |
| 380 | if (bot > im.h-1) bot = im.h-1; |
| 381 | |
| 382 | draw_box_width(im, left, top, right, bot, width, red, green, blue); |
| 383 | yolo_image label = get_label(alphabet, labelstr, (im.h*.03)); |
| 384 | draw_label(im, top + width, left, label, rgb); |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | static void print_shape(int layer, const ggml_tensor * t) |
| 390 | { |
| 391 | printf("Layer %2d output shape: %3d x %3d x %4d x %3d\n", layer, (int)t->ne[0], (int)t->ne[1], (int)t->ne[2], (int)t->ne[3]); |
| 392 | } |
| 393 | |
| 394 | static struct ggml_cgraph * build_graph(struct ggml_context * ctx_cgraph, const yolo_model & model) { |
| 395 | struct ggml_cgraph * gf = ggml_new_graph(ctx_cgraph); |
| 396 | |
| 397 | struct ggml_tensor * input = ggml_new_tensor_4d(ctx_cgraph, GGML_TYPE_F32, model.width, model.height, 3, 1); |
| 398 | ggml_set_name(input, "input"); |
| 399 | struct ggml_tensor * result = apply_conv2d(ctx_cgraph, input, model.conv2d_layers[0]); |
| 400 | print_shape(0, result); |
| 401 | result = ggml_pool_2d(ctx_cgraph, result, GGML_OP_POOL_MAX, 2, 2, 2, 2, 0, 0); |
| 402 | print_shape(1, result); |
| 403 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[1]); |
| 404 | print_shape(2, result); |
| 405 | result = ggml_pool_2d(ctx_cgraph, result, GGML_OP_POOL_MAX, 2, 2, 2, 2, 0, 0); |
| 406 | print_shape(3, result); |
| 407 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[2]); |
| 408 | print_shape(4, result); |
| 409 | result = ggml_pool_2d(ctx_cgraph, result, GGML_OP_POOL_MAX, 2, 2, 2, 2, 0, 0); |
| 410 | print_shape(5, result); |
| 411 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[3]); |
| 412 | print_shape(6, result); |
| 413 | result = ggml_pool_2d(ctx_cgraph, result, GGML_OP_POOL_MAX, 2, 2, 2, 2, 0, 0); |
| 414 | print_shape(7, result); |
| 415 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[4]); |
| 416 | struct ggml_tensor * layer_8 = result; |
| 417 | print_shape(8, result); |
| 418 | result = ggml_pool_2d(ctx_cgraph, result, GGML_OP_POOL_MAX, 2, 2, 2, 2, 0, 0); |
| 419 | print_shape(9, result); |
| 420 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[5]); |
| 421 | print_shape(10, result); |
| 422 | result = ggml_pool_2d(ctx_cgraph, result, GGML_OP_POOL_MAX, 2, 2, 1, 1, 0.5, 0.5); |
| 423 | print_shape(11, result); |
| 424 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[6]); |
| 425 | print_shape(12, result); |
| 426 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[7]); |
| 427 | struct ggml_tensor * layer_13 = result; |
| 428 | print_shape(13, result); |
| 429 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[8]); |
| 430 | print_shape(14, result); |
| 431 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[9]); |
| 432 | struct ggml_tensor * layer_15 = result; |
| 433 | ggml_set_output(layer_15); |
| 434 | ggml_set_name(layer_15, "layer_15"); |
| 435 | |
| 436 | print_shape(15, result); |
| 437 | result = apply_conv2d(ctx_cgraph, layer_13, model.conv2d_layers[10]); |
| 438 | print_shape(18, result); |
| 439 | result = ggml_upscale(ctx_cgraph, result, 2, GGML_SCALE_MODE_NEAREST); |
| 440 | print_shape(19, result); |
| 441 | result = ggml_concat(ctx_cgraph, result, layer_8, 2); |
| 442 | print_shape(20, result); |
| 443 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[11]); |
| 444 | print_shape(21, result); |
| 445 | result = apply_conv2d(ctx_cgraph, result, model.conv2d_layers[12]); |
| 446 | struct ggml_tensor * layer_22 = result; |
| 447 | ggml_set_output(layer_22); |
| 448 | ggml_set_name(layer_22, "layer_22"); |
| 449 | print_shape(22, result); |
| 450 | |
| 451 | ggml_build_forward_expand(gf, layer_15); |
| 452 | ggml_build_forward_expand(gf, layer_22); |
| 453 | return gf; |
| 454 | } |
| 455 | |
| 456 | void detect(yolo_image & img, struct ggml_cgraph * gf, const yolo_model & model, float thresh, const std::vector<std::string> & labels, const std::vector<yolo_image> & alphabet) |
| 457 | { |
| 458 | std::vector<detection> detections; |
| 459 | yolo_image sized = letterbox_image(img, model.width, model.height); |
| 460 | struct ggml_tensor * input = ggml_graph_get_tensor(gf, "input"); |
| 461 | ggml_backend_tensor_set(input, sized.data.data(), 0, ggml_nbytes(input)); |
| 462 | |
| 463 | if (ggml_backend_graph_compute(model.backend, gf) != GGML_STATUS_SUCCESS) { |
| 464 | fprintf(stderr, "%s: ggml_backend_graph_compute() failed\n", __func__); |
| 465 | return; |
| 466 | } |
| 467 | |
| 468 | struct ggml_tensor * layer_15 = ggml_graph_get_tensor(gf, "layer_15"); |
| 469 | yolo_layer yolo16{ 80, {3, 4, 5}, {10, 14, 23, 27, 37,58, 81, 82, 135, 169, 344, 319}, layer_15}; |
| 470 | apply_yolo(yolo16); |
| 471 | get_yolo_detections(yolo16, detections, img.w, img.h, model.width, model.height, thresh); |
| 472 | |
| 473 | struct ggml_tensor * layer_22 = ggml_graph_get_tensor(gf, "layer_22"); |
| 474 | yolo_layer yolo23{ 80, {0, 1, 2}, {10, 14, 23, 27, 37,58, 81, 82, 135, 169, 344, 319}, layer_22}; |
| 475 | apply_yolo(yolo23); |
| 476 | get_yolo_detections(yolo23, detections, img.w, img.h, model.width, model.height, thresh); |
| 477 | |
| 478 | do_nms_sort(detections, yolo23.classes, .45); |
| 479 | draw_detections(img, detections, thresh, labels, alphabet); |
| 480 | } |
| 481 | |
| 482 | struct yolo_params { |
| 483 | float thresh = 0.5; |
| 484 | std::string model = "yolov3-tiny.gguf"; |
| 485 | std::string fname_inp = "input.jpg"; |
| 486 | std::string fname_out = "predictions.jpg"; |
| 487 | int n_threads = std::max(1U, std::thread::hardware_concurrency()/2); |
| 488 | std::string device; |
| 489 | }; |
| 490 | |
| 491 | void yolo_print_usage(int argc, char ** argv, const yolo_params & params) { |
| 492 | fprintf(stderr, "usage: %s [options]\n", argv[0]); |
| 493 | fprintf(stderr, "\n"); |
| 494 | fprintf(stderr, "options:\n"); |
| 495 | fprintf(stderr, " -h, --help show this help message and exit\n"); |
| 496 | fprintf(stderr, " -d, --device DEV device to use\n"); |
| 497 | fprintf(stderr, " -t, --threads N number of threads for the CPU backend (default: %d)\n", params.n_threads); |
| 498 | fprintf(stderr, " -th, --thresh T detection threshold (default: %.2f)\n", params.thresh); |
| 499 | fprintf(stderr, " -m, --model FNAME model path (default: %s)\n", params.model.c_str()); |
| 500 | fprintf(stderr, " -i, --inp FNAME input file (default: %s)\n", params.fname_inp.c_str()); |
| 501 | fprintf(stderr, " -o, --out FNAME output file (default: %s)\n", params.fname_out.c_str()); |
| 502 | fprintf(stderr, "\n"); |
| 503 | } |
| 504 | |
| 505 | bool yolo_params_parse(int argc, char ** argv, yolo_params & params) { |
| 506 | for (int i = 1; i < argc; i++) { |
| 507 | std::string arg = argv[i]; |
| 508 | if (arg == "-th" || arg == "--thresh") { |
| 509 | params.thresh = std::stof(argv[++i]); |
| 510 | if (params.thresh < 0 || params.thresh > 1) { |
| 511 | fprintf(stderr, "error: invalid threshold: %.2f\n", params.thresh); |
| 512 | return false; |
| 513 | } |
| 514 | } else if (arg == "-m" || arg == "--model") { |
| 515 | params.model = argv[++i]; |
| 516 | } else if (arg == "-i" || arg == "--inp") { |
| 517 | params.fname_inp = argv[++i]; |
| 518 | } else if (arg == "-o" || arg == "--out") { |
| 519 | params.fname_out = argv[++i]; |
| 520 | } else if (arg == "-t" || arg == "--threads") { |
| 521 | if (++i >= argc) { |
| 522 | return false; |
| 523 | } |
| 524 | params.n_threads = std::stoi(argv[i]); |
| 525 | if (params.n_threads <= 0) { |
| 526 | fprintf(stderr, "error: invalid number of threads: %d\n", params.n_threads); |
| 527 | return false; |
| 528 | } |
| 529 | } else if (arg == "-d" || arg == "--device") { |
| 530 | if (++i >= argc) { |
| 531 | return false; |
| 532 | } |
| 533 | params.device = argv[i]; |
| 534 | if (ggml_backend_dev_by_name(params.device.c_str()) == nullptr) { |
| 535 | fprintf(stderr, "error: unknown device: %s\n", params.device.c_str()); |
| 536 | fprintf(stderr, "available devices:\n"); |
| 537 | for (size_t i = 0; i < ggml_backend_dev_count(); i++) { |
| 538 | auto * dev = ggml_backend_dev_get(i); |
| 539 | size_t free, total; |
| 540 | ggml_backend_dev_memory(dev, &free, &total); |
| 541 | printf(" %s: %s (%zu MiB, %zu MiB free)\n", ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), total / 1024 / 1024, free / 1024 / 1024); |
| 542 | } |
| 543 | return false; |
| 544 | } |
| 545 | } else if (arg == "-h" || arg == "--help") { |
| 546 | yolo_print_usage(argc, argv, params); |
| 547 | exit(0); |
| 548 | } else { |
| 549 | fprintf(stderr, "error: unknown argument: %s\n", arg.c_str()); |
| 550 | yolo_print_usage(argc, argv, params); |
| 551 | exit(0); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | return true; |
| 556 | } |
| 557 | |
| 558 | static ggml_backend_t create_backend(const yolo_params & params) { |
| 559 | ggml_backend_t backend = nullptr; |
| 560 | |
| 561 | if (!params.device.empty()) { |
| 562 | ggml_backend_dev_t dev = ggml_backend_dev_by_name(params.device.c_str()); |
| 563 | if (dev) { |
| 564 | backend = ggml_backend_dev_init(dev, nullptr); |
| 565 | if (!backend) { |
| 566 | fprintf(stderr, "Failed to create backend for device %s\n", params.device.c_str()); |
| 567 | return nullptr; |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | // try to initialize a GPU backend first |
| 573 | if (!backend) { |
| 574 | backend = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr); |
| 575 | } |
| 576 | |
| 577 | // if there aren't GPU backends fallback to CPU backend |
| 578 | if (!backend) { |
| 579 | backend = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr); |
| 580 | } |
| 581 | |
| 582 | if (backend) { |
| 583 | fprintf(stderr, "%s: using %s backend\n", __func__, ggml_backend_name(backend)); |
| 584 | |
| 585 | // set the number of threads |
| 586 | ggml_backend_dev_t dev = ggml_backend_get_device(backend); |
| 587 | ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr; |
| 588 | if (reg) { |
| 589 | auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads"); |
| 590 | if (ggml_backend_set_n_threads_fn) { |
| 591 | ggml_backend_set_n_threads_fn(backend, params.n_threads); |
| 592 | } |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | return backend; |
| 597 | } |
| 598 | |
| 599 | int main(int argc, char *argv[]) |
| 600 | { |
| 601 | ggml_backend_load_all(); |
| 602 | ggml_time_init(); |
| 603 | yolo_model model; |
| 604 | |
| 605 | yolo_params params; |
| 606 | if (!yolo_params_parse(argc, argv, params)) { |
| 607 | return 1; |
| 608 | } |
| 609 | model.backend = create_backend(params); |
| 610 | if (!model.backend) { |
| 611 | fprintf(stderr, "Failed to create backend\n"); |
| 612 | return 1; |
| 613 | } |
| 614 | |
| 615 | if (!load_model(params.model, model)) { |
| 616 | fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str()); |
| 617 | return 1; |
| 618 | } |
| 619 | yolo_image img(0,0,0); |
| 620 | if (!load_image(params.fname_inp.c_str(), img)) { |
| 621 | fprintf(stderr, "%s: failed to load image from '%s'\n", __func__, params.fname_inp.c_str()); |
| 622 | return 1; |
| 623 | } |
| 624 | std::vector<std::string> labels; |
| 625 | if (!load_labels("data/coco.names", labels)) { |
| 626 | fprintf(stderr, "%s: failed to load labels from 'data/coco.names'\n", __func__); |
| 627 | return 1; |
| 628 | } |
| 629 | std::vector<yolo_image> alphabet; |
| 630 | if (!load_alphabet(alphabet)) { |
| 631 | fprintf(stderr, "%s: failed to load alphabet\n", __func__); |
| 632 | return 1; |
| 633 | } |
| 634 | |
| 635 | struct ggml_init_params params0 = { |
| 636 | /*.mem_size =*/ ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead(), |
| 637 | /*.mem_buffer =*/ NULL, |
| 638 | /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_gallocr_alloc_graph() |
| 639 | }; |
| 640 | struct ggml_context * ctx_cgraph = ggml_init(params0); |
| 641 | struct ggml_cgraph * gf = build_graph(ctx_cgraph, model); |
| 642 | |
| 643 | ggml_gallocr_t allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(model.backend)); |
| 644 | ggml_gallocr_alloc_graph(allocr, gf); |
| 645 | |
| 646 | const int64_t t_start_ms = ggml_time_ms(); |
| 647 | detect(img, gf, model, params.thresh, labels, alphabet); |
| 648 | const int64_t t_detect_ms = ggml_time_ms() - t_start_ms; |
| 649 | if (!save_image(img, params.fname_out.c_str(), 80)) { |
| 650 | fprintf(stderr, "%s: failed to save image to '%s'\n", __func__, params.fname_out.c_str()); |
| 651 | return 1; |
| 652 | } |
| 653 | printf("Detected objects saved in '%s' (time: %f sec.)\n", params.fname_out.c_str(), t_detect_ms / 1000.0f); |
| 654 | |
| 655 | ggml_free(ctx_cgraph); |
| 656 | ggml_gallocr_free(allocr); |
| 657 | ggml_free(model.ctx); |
| 658 | ggml_backend_buffer_free(model.buffer); |
| 659 | ggml_backend_free(model.backend); |
| 660 | return 0; |
| 661 | } |