interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / examples / sam / sam.cpp

2362 lines · 102862 bytes Raw Blame History
1#define _USE_MATH_DEFINES // for M_PI
2#define _CRT_SECURE_NO_DEPRECATE // Disables ridiculous "unsafe" warnigns on Windows
3
4#include "ggml.h"
5#include "ggml-cpu.h"
6#include "ggml-alloc.h"
7#include "ggml-backend.h"
8#define STB_IMAGE_IMPLEMENTATION
9#include "stb_image.h"
10#define STB_IMAGE_WRITE_IMPLEMENTATION
11#include "stb_image_write.h"
12
13#include <cassert>
14#include <cmath>
15#include <cstddef>
16#include <cstdio>
17#include <cstring>
18#include <fstream>
19#include <map>
20#include <string>
21#include <vector>
22#include <thread>
23#include <cinttypes>
24
25#if defined(_MSC_VER)
26#pragma warning(disable: 4244 4267) // possible loss of data
27#endif
28
29// default hparams (ViT-B SAM)
30struct sam_hparams {
31 int32_t n_enc_state = 768;
32 int32_t n_enc_layer = 12;
33 int32_t n_enc_head = 12;
34 int32_t n_enc_out_chans = 256;
35 int32_t n_pt_embd = 4;
36 int32_t n_dec_heads = 8;
37 int32_t ftype = 1;
38 float mask_threshold = 0.f;
39 float iou_threshold = 0.88f;
40 float stability_score_threshold = 0.95f;
41 float stability_score_offset = 1.0f;
42 float eps = 1e-6f;
43 float eps_decoder_transformer = 1e-5f;
44
45 int32_t n_enc_head_dim() const { return n_enc_state / n_enc_head; }
46 int32_t n_img_size() const { return 1024; }
47 int32_t n_window_size() const { return 14; }
48 int32_t n_patch_size() const { return 16; }
49 int32_t n_img_embd() const { return n_img_size() / n_patch_size(); }
50
51 std::vector<int32_t> global_attn_indices() const {
52 switch (n_enc_state) {
53 case 768: return { 2, 5, 8, 11 };
54 case 1024: return { 5, 11, 17, 23 };
55 case 1280: return { 7, 15, 23, 31 };
56 default:
57 {
58 fprintf(stderr, "%s: unsupported n_enc_state = %d\n", __func__, n_enc_state);
59 } break;
60 };
61
62 return {};
63 }
64
65 bool is_global_attn(int32_t layer) const {
66 const auto indices = global_attn_indices();
67
68 for (const auto & idx : indices) {
69 if (layer == idx) {
70 return true;
71 }
72 }
73
74 return false;
75 }
76};
77
78struct sam_layer_enc {
79 struct ggml_tensor * norm1_w;
80 struct ggml_tensor * norm1_b;
81
82 struct ggml_tensor * rel_pos_w;
83 struct ggml_tensor * rel_pos_h;
84
85 struct ggml_tensor * qkv_w;
86 struct ggml_tensor * qkv_b;
87
88 struct ggml_tensor * proj_w;
89 struct ggml_tensor * proj_b;
90
91 struct ggml_tensor * norm2_w;
92 struct ggml_tensor * norm2_b;
93
94 struct ggml_tensor * mlp_lin1_w;
95 struct ggml_tensor * mlp_lin1_b;
96
97 struct ggml_tensor * mlp_lin2_w;
98 struct ggml_tensor * mlp_lin2_b;
99};
100
101struct sam_encoder_image {
102 struct ggml_tensor * pe;
103
104 struct ggml_tensor * proj_w;
105 struct ggml_tensor * proj_b;
106
107 struct ggml_tensor * neck_conv_0;
108 struct ggml_tensor * neck_norm_0_w;
109 struct ggml_tensor * neck_norm_0_b;
110 struct ggml_tensor * neck_conv_1;
111 struct ggml_tensor * neck_norm_1_w;
112 struct ggml_tensor * neck_norm_1_b;
113
114 std::vector<sam_layer_enc> layers;
115};
116
117struct sam_encoder_prompt {
118 struct ggml_tensor * pe;
119
120 struct ggml_tensor * not_a_pt_embd_w;
121 std::vector<struct ggml_tensor *> pt_embd;
122
123 struct ggml_tensor * no_mask_embd_w;
124 //std::vector<struct ggml_tensor *> mask_down_w;
125 //std::vector<struct ggml_tensor *> mask_down_b;
126};
127
128struct sam_layer_dec_transformer_attn {
129 // q_proj
130 struct ggml_tensor * q_w;
131 struct ggml_tensor * q_b;
132
133 // k_proj
134 struct ggml_tensor * k_w;
135 struct ggml_tensor * k_b;
136
137 // v_proj
138 struct ggml_tensor * v_w;
139 struct ggml_tensor * v_b;
140
141 // out_proj
142 struct ggml_tensor * out_w;
143 struct ggml_tensor * out_b;
144};
145
146struct sam_layer_dec_transformer {
147 sam_layer_dec_transformer_attn self_attn;
148
149 // norm1
150 struct ggml_tensor * norm1_w;
151 struct ggml_tensor * norm1_b;
152
153 sam_layer_dec_transformer_attn cross_attn_token_to_img;
154
155 // norm2
156 struct ggml_tensor * norm2_w;
157 struct ggml_tensor * norm2_b;
158
159 // mlp.lin1
160 struct ggml_tensor * mlp_lin1_w;
161 struct ggml_tensor * mlp_lin1_b;
162
163 // mlp.lin2
164 struct ggml_tensor * mlp_lin2_w;
165 struct ggml_tensor * mlp_lin2_b;
166
167 // norm3
168 struct ggml_tensor * norm3_w;
169 struct ggml_tensor * norm3_b;
170
171 // norm4
172 struct ggml_tensor * norm4_w;
173 struct ggml_tensor * norm4_b;
174
175 sam_layer_dec_transformer_attn cross_attn_img_to_token;
176};
177
178struct sam_layer_dec_output_hypernet_mlps {
179 // mlps_*.layers.0
180 struct ggml_tensor * w_0;
181 struct ggml_tensor * b_0;
182
183 // mlps_*.layers.1
184 struct ggml_tensor * w_1;
185 struct ggml_tensor * b_1;
186
187 // mlps_*.layers.2
188 struct ggml_tensor * w_2;
189 struct ggml_tensor * b_2;
190};
191
192struct sam_decoder_mask {
193 std::vector<sam_layer_dec_transformer> transformer_layers;
194
195 // trasnformer.final_attn_token_to_image
196 sam_layer_dec_transformer_attn transformer_final_attn_token_to_img;
197
198 // transformer.norm_final
199 struct ggml_tensor * transformer_norm_final_w;
200 struct ggml_tensor * transformer_norm_final_b;
201
202 // output_upscaling.0
203 struct ggml_tensor * output_upscaling_0_w;
204 struct ggml_tensor * output_upscaling_0_b;
205
206 // output_upscaling.1
207 struct ggml_tensor * output_upscaling_1_w;
208 struct ggml_tensor * output_upscaling_1_b;
209
210 // output_upscaling.3
211 struct ggml_tensor * output_upscaling_3_w;
212 struct ggml_tensor * output_upscaling_3_b;
213
214 // output_hypernetworks_mlps
215 std::vector<sam_layer_dec_output_hypernet_mlps> output_hypernet_mlps;
216
217 // iou_prediction_head.0
218 struct ggml_tensor * iou_prediction_head_0_w;
219 struct ggml_tensor * iou_prediction_head_0_b;
220
221 // iou_prediction_head.1
222 struct ggml_tensor * iou_prediction_head_1_w;
223 struct ggml_tensor * iou_prediction_head_1_b;
224
225 // iou_prediction_head.2
226 struct ggml_tensor * iou_prediction_head_2_w;
227 struct ggml_tensor * iou_prediction_head_2_b;
228
229 // iou_token.weight
230 struct ggml_tensor * iou_token_w;
231
232 // mask_tokens.weight
233 struct ggml_tensor * mask_tokens_w;
234};
235
236
237struct sam_state {
238 struct ggml_tensor * embd_img;
239
240 struct ggml_tensor * low_res_masks;
241 struct ggml_tensor * iou_predictions;
242
243 //struct ggml_tensor * tmp_save = {};
244
245 struct ggml_context * ctx;
246
247 // buffer for `ggml_graph_plan.work_data`
248 std::vector<uint8_t> work_buffer;
249 // buffers to evaluate the model
250 std::vector<uint8_t> buf_compute_img_enc;
251
252 std::vector<uint8_t> buf_compute_fast;
253
254 ggml_gallocr_t allocr = {};
255};
256
257// void save_tensor(sam_state& state, struct ggml_tensor * t, struct ggml_cgraph * gf) {
258// if (!state.tmp_save) {
259// state.tmp_save = ggml_new_tensor(state.ctx, t->type, t->n_dims, t->ne);
260// }
261// struct ggml_tensor * tmp0 = ggml_cpy(state.ctx, t, state.tmp_save);
262// ggml_build_forward_expand(gf, tmp0);
263// }
264
265struct sam_model {
266 sam_hparams hparams;
267
268 sam_encoder_image enc_img;
269 sam_encoder_prompt enc_prompt;
270 sam_decoder_mask dec;
271
272 //
273 struct ggml_context * ctx;
274 std::map<std::string, struct ggml_tensor *> tensors;
275};
276
277struct sam_point {
278 float x;
279 float y;
280};
281
282struct sam_box {
283 float x1;
284 float y1;
285 float x2;
286 float y2;
287};
288
289// RGB uint8 image
290struct sam_image_u8 {
291 int nx;
292 int ny;
293
294 std::vector<uint8_t> data;
295};
296
297// RGB float32 image
298// Memory layout: RGBRGBRGB...
299struct sam_image_f32 {
300 int nx;
301 int ny;
302
303 std::vector<float> data;
304};
305
306enum sam_prompt_type {
307 SAM_PROMPT_TYPE_POINT = 0,
308 SAM_PROMPT_TYPE_BOX = 1,
309};
310
311struct sam_prompt {
312 sam_prompt_type prompt_type = SAM_PROMPT_TYPE_POINT;
313 sam_point pt = { 414.375f, 162.796875f, };
314 sam_box box = { 368.0f, 144.0f, 441.0f, 173.0f };
315};
316
317struct sam_params {
318 int32_t seed = -1; // RNG seed
319 int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
320
321 std::string model = "models/sam-vit-b/ggml-model-f16.bin"; // model path
322 std::string fname_inp = "img.jpg";
323 std::string fname_out = "img.out";
324 float mask_threshold = 0.f;
325 float iou_threshold = 0.88f;
326 float stability_score_threshold = 0.95f;
327 float stability_score_offset = 1.0f;
328 float eps = 1e-6f;
329 float eps_decoder_transformer = 1e-5f;
330
331 sam_prompt prompt;
332 bool multimask_output = true;
333};
334
335void print_t_f32(const char* title, struct ggml_tensor * t, int n = 10) {
336 printf("%s\n", title);
337 float * data = (float *)t->data;
338 printf("dims: % " PRId64 " % " PRId64 " % " PRId64 " % " PRId64 " f32\n", t->ne[0], t->ne[1], t->ne[2], t->ne[3]);
339 printf("First & Last %d elements:\n", n);
340 for (int i = 0; i < std::min((int) (t->ne[0]*t->ne[1]), n); i++) {
341 printf("%.5f ", data[i]);
342 if (i != 0 && i % t->ne[0] == 0) {
343 printf("\n");
344 }
345 }
346 printf("\n");
347 for (int i = 0; i < std::min((int) (t->ne[0]*t->ne[1]), n); i++) {
348 printf("%.5f ", data[ggml_nelements(t) - n + i]);
349 if ((ggml_nelements(t) - n + i) % t->ne[0] == 0) {
350 printf("\n");
351 }
352 }
353 printf("\n");
354 double sum = 0.0;
355 for (int i = 0; i < ggml_nelements(t); i++) {
356 sum += data[i];
357 }
358 printf("sum: %f\n\n", sum);
359}
360
361static void ggml_disconnect_node_from_graph(ggml_tensor * t) {
362 t->op = GGML_OP_NONE;
363 for (int i = 0; i < GGML_MAX_SRC; i++) {
364 t->src[i] = NULL;
365 }
366}
367
368static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
369 struct ggml_cplan plan = ggml_graph_plan(graph, n_threads, nullptr);
370
371 if (plan.work_size > 0) {
372 buf.resize(plan.work_size);
373 plan.work_data = buf.data();
374 }
375
376 ggml_graph_compute(graph, &plan);
377}
378
379static void ggml_sam_sin(struct ggml_tensor * dst , const struct ggml_tensor * src, int ith, int nth, void * userdata) {
380 GGML_ASSERT(userdata == NULL);
381 GGML_ASSERT(ggml_are_same_shape(dst, src));
382 GGML_ASSERT(ggml_is_contiguous(dst));
383 GGML_ASSERT(ggml_is_contiguous(src));
384
385 const float * src_data = ggml_get_data_f32(src);
386 float * dst_data = ggml_get_data_f32(dst);
387
388 const int ne = (int)ggml_nelements(dst);
389 const int dr = (ne + nth - 1) / nth;
390 const int ie0 = dr * ith;
391 const int ie1 = std::min(ie0 + dr, ne);
392
393 for (int i = ie0; i < ie1; ++i) {
394 dst_data[i] = sinf(src_data[i]);
395 }
396}
397
398static void ggml_sam_cos(struct ggml_tensor * dst , const struct ggml_tensor * src, int ith, int nth, void * userdata) {
399 GGML_ASSERT(userdata == NULL);
400 GGML_ASSERT(ggml_are_same_shape(dst, src));
401 GGML_ASSERT(ggml_is_contiguous(dst));
402 GGML_ASSERT(ggml_is_contiguous(src));
403
404 const float * src_data = ggml_get_data_f32(src);
405 float * dst_data = ggml_get_data_f32(dst);
406
407 const int ne = (int)ggml_nelements(dst);
408 const int dr = (ne + nth - 1) / nth;
409 const int ie0 = dr * ith;
410 const int ie1 = std::min(ie0 + dr, ne);
411
412 for (int i = ie0; i < ie1; ++i) {
413 dst_data[i] = cosf(src_data[i]);
414 }
415}
416
417bool sam_image_load_from_file(const std::string & fname, sam_image_u8 & img) {
418 int nx, ny, nc;
419 auto data = stbi_load(fname.c_str(), &nx, &ny, &nc, 3);
420 if (!data) {
421 fprintf(stderr, "%s: failed to load '%s'\n", __func__, fname.c_str());
422 return false;
423 }
424
425 img.nx = nx;
426 img.ny = ny;
427 img.data.resize(nx * ny * 3);
428 memcpy(img.data.data(), data, nx * ny * 3);
429
430 stbi_image_free(data);
431
432 return true;
433}
434
435// ref: https://github.com/facebookresearch/segment-anything/blob/efeab7296ab579d4a261e554eca80faf6b33924a/segment_anything/modeling/sam.py#L164
436// resize largest dimension to 1024
437// normalize: x = (x - mean) / std
438// mean = [123.675, 116.28, 103.53]
439// std = [58.395, 57.12, 57.375]
440// TODO: why are these hardcoded !?
441// pad to 1024x1024
442// TODO: for some reason, this is not numerically identical to pytorch's interpolation
443bool sam_image_preprocess(const sam_image_u8 & img, sam_image_f32 & res) {
444 const int nx = img.nx;
445 const int ny = img.ny;
446
447 const int nx2 = 1024;
448 const int ny2 = 1024;
449
450 res.nx = nx2;
451 res.ny = ny2;
452 res.data.resize(3*nx2*ny2);
453
454 const float scale = std::max(nx, ny) / 1024.0f;
455
456 fprintf(stderr, "%s: scale = %f\n", __func__, scale);
457
458 const int nx3 = int(nx/scale + 0.5f);
459 const int ny3 = int(ny/scale + 0.5f);
460
461 const float m3[3] = { 123.675f, 116.280f, 103.530f };
462 const float s3[3] = { 58.395f, 57.120f, 57.375f };
463
464 for (int y = 0; y < ny3; y++) {
465 for (int x = 0; x < nx3; x++) {
466 for (int c = 0; c < 3; c++) {
467 // linear interpolation
468 const float sx = (x + 0.5f)*scale - 0.5f;
469 const float sy = (y + 0.5f)*scale - 0.5f;
470
471 const int x0 = std::max(0, (int) std::floor(sx));
472 const int y0 = std::max(0, (int) std::floor(sy));
473
474 const int x1 = std::min(x0 + 1, nx - 1);
475 const int y1 = std::min(y0 + 1, ny - 1);
476
477 const float dx = sx - x0;
478 const float dy = sy - y0;
479
480 const int j00 = 3*(y0*nx + x0) + c;
481 const int j01 = 3*(y0*nx + x1) + c;
482 const int j10 = 3*(y1*nx + x0) + c;
483 const int j11 = 3*(y1*nx + x1) + c;
484
485 const float v00 = img.data[j00];
486 const float v01 = img.data[j01];
487 const float v10 = img.data[j10];
488 const float v11 = img.data[j11];
489
490 const float v0 = v00*(1.0f - dx) + v01*dx;
491 const float v1 = v10*(1.0f - dx) + v11*dx;
492
493 const float v = v0*(1.0f - dy) + v1*dy;
494
495 const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
496
497 const int i = 3*(y*nx3 + x) + c;
498
499 res.data[i] = (float(v2) - m3[c]) / s3[c];
500 }
501 }
502 }
503
504 return true;
505}
506
507// load the model's weights from a file
508bool sam_model_load(const sam_params & params, sam_model & model) {
509 fprintf(stderr, "%s: loading model from '%s' - please wait ...\n", __func__, params.model.c_str());
510
511 auto fin = std::ifstream(params.model, std::ios::binary);
512 if (!fin) {
513 fprintf(stderr, "%s: failed to open '%s'\n", __func__, params.model.c_str());
514 return false;
515 }
516
517 // verify magic
518 {
519 uint32_t magic;
520 fin.read((char *) &magic, sizeof(magic));
521 if (magic != 0x67676d6c) {
522 fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, params.model.c_str());
523 return false;
524 }
525 }
526
527 // load hparams
528 {
529 // Override defaults with user choices
530 model.hparams.mask_threshold = params.mask_threshold;
531 model.hparams.iou_threshold = params.iou_threshold;
532 model.hparams.stability_score_threshold = params.stability_score_threshold;
533 model.hparams.stability_score_offset = params.stability_score_offset;
534 model.hparams.eps = params.eps;
535 model.hparams.eps_decoder_transformer = params.eps_decoder_transformer;
536
537 auto & hparams = model.hparams;
538
539 fin.read((char *) &hparams.n_enc_state, sizeof(hparams.n_enc_state));
540 fin.read((char *) &hparams.n_enc_layer, sizeof(hparams.n_enc_layer));
541 fin.read((char *) &hparams.n_enc_head, sizeof(hparams.n_enc_head));
542 fin.read((char *) &hparams.n_enc_out_chans, sizeof(hparams.n_enc_out_chans));
543 fin.read((char *) &hparams.n_pt_embd, sizeof(hparams.n_pt_embd));
544 fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
545
546 const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
547
548 printf("%s: n_enc_state = %d\n", __func__, hparams.n_enc_state);
549 printf("%s: n_enc_layer = %d\n", __func__, hparams.n_enc_layer);
550 printf("%s: n_enc_head = %d\n", __func__, hparams.n_enc_head);
551 printf("%s: n_enc_out_chans = %d\n", __func__, hparams.n_enc_out_chans);
552 printf("%s: n_pt_embd = %d\n", __func__, hparams.n_pt_embd);
553 printf("%s: ftype = %d\n", __func__, hparams.ftype);
554 printf("%s: qntvr = %d\n", __func__, qntvr);
555
556 hparams.ftype %= GGML_QNT_VERSION_FACTOR;
557
558 }
559
560 // for the big tensors, we have the option to store the data in 16-bit floats or quantized
561 // in order to save memory and also to speed up the computation
562 ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
563 if (wtype == GGML_TYPE_COUNT) {
564 fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n",
565 __func__, params.model.c_str(), model.hparams.ftype);
566 return false;
567 }
568
569 auto & ctx = model.ctx;
570
571 const size_t ctx_size = [&]() {
572 size_t ctx_size = 0;
573
574 const auto & hparams = model.hparams;
575
576 const int32_t n_enc_state = hparams.n_enc_state;
577 const int32_t n_enc_layer = hparams.n_enc_layer;
578 const int32_t n_enc_head_dim = hparams.n_enc_head_dim();
579 const int32_t n_enc_out_chans = hparams.n_enc_out_chans;
580 const int32_t n_pt_embd = hparams.n_pt_embd;
581
582 const int32_t n_enc_layer_local = hparams.global_attn_indices().size();
583 const int32_t n_enc_layer_global = n_enc_layer - n_enc_layer_local;
584
585 const int32_t n_img_embd = hparams.n_img_embd();
586 const int32_t n_window_size = hparams.n_window_size();
587 const int32_t n_patch_size = hparams.n_patch_size();
588
589 // image encoder
590 {
591 ctx_size += n_enc_state*n_img_embd*n_img_embd*ggml_type_size(GGML_TYPE_F32);
592
593 ctx_size += n_enc_state*3*n_patch_size*n_patch_size*ggml_type_size(GGML_TYPE_F16);
594 ctx_size += n_enc_state*ggml_type_size(GGML_TYPE_F32);
595
596 ctx_size += n_enc_state*n_enc_out_chans*1*1*ggml_type_size(GGML_TYPE_F16);
597 ctx_size += n_enc_out_chans*n_enc_out_chans*3*3*ggml_type_size(GGML_TYPE_F16);
598
599 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
600 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
601
602 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
603 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
604 }
605
606 // image encoder layers
607 {
608 ctx_size += n_enc_layer*n_enc_state*ggml_type_size(GGML_TYPE_F32);
609 ctx_size += n_enc_layer*n_enc_state*ggml_type_size(GGML_TYPE_F32);
610
611 ctx_size += n_enc_layer_global*n_enc_head_dim*(2*n_img_embd - 1)*ggml_type_size(GGML_TYPE_F16);
612 ctx_size += n_enc_layer_global*n_enc_head_dim*(2*n_img_embd - 1)*ggml_type_size(GGML_TYPE_F16);
613
614 ctx_size += n_enc_layer_local*n_enc_head_dim*(2*n_window_size - 1)*ggml_type_size(GGML_TYPE_F16);
615 ctx_size += n_enc_layer_local*n_enc_head_dim*(2*n_window_size - 1)*ggml_type_size(GGML_TYPE_F16);
616
617 ctx_size += n_enc_layer*3*n_enc_state*n_enc_state*ggml_type_size(GGML_TYPE_F16);
618 ctx_size += n_enc_layer*3*n_enc_state* ggml_type_size(GGML_TYPE_F32);
619
620 ctx_size += n_enc_layer*n_enc_state*n_enc_state*ggml_type_size(GGML_TYPE_F16);
621 ctx_size += n_enc_layer*n_enc_state* ggml_type_size(GGML_TYPE_F32);
622
623 ctx_size += n_enc_layer*n_enc_state*ggml_type_size(GGML_TYPE_F32);
624 ctx_size += n_enc_layer*n_enc_state*ggml_type_size(GGML_TYPE_F32);
625
626 ctx_size += n_enc_layer*4*n_enc_state*n_enc_state*ggml_type_size(GGML_TYPE_F16);
627 ctx_size += n_enc_layer*4*n_enc_state* ggml_type_size(GGML_TYPE_F32);
628
629 ctx_size += n_enc_layer*4*n_enc_state*n_enc_state*ggml_type_size(GGML_TYPE_F16);
630 ctx_size += n_enc_layer*4*n_enc_state* ggml_type_size(GGML_TYPE_F32);
631 }
632
633 ctx_size += (8 + 14*n_enc_layer)*ggml_tensor_overhead();
634
635 // prompt encoder
636 {
637 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F16); // 2*(n_enc_out_chans/2)
638
639 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
640 ctx_size += n_pt_embd*n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
641 }
642
643 ctx_size += (2 + n_pt_embd)*ggml_tensor_overhead();
644
645 // mask decoder
646 {
647 //transformer
648 {
649 const int tfm_layers_count = 2;
650 const int qkv_count = 3;
651 const int norm_count = 4;
652 const int n_hypernet_mpls_count = 4;
653
654 // self_attn
655 ctx_size += tfm_layers_count*qkv_count*n_enc_state*n_enc_state*ggml_type_size(GGML_TYPE_F16);
656 ctx_size += tfm_layers_count*qkv_count*n_enc_state* ggml_type_size(GGML_TYPE_F32);
657 ctx_size += tfm_layers_count*n_enc_state* ggml_type_size(GGML_TYPE_F32);
658
659 // all norms
660 ctx_size += tfm_layers_count*norm_count*n_enc_state*ggml_type_size(GGML_TYPE_F32);
661 ctx_size += tfm_layers_count*norm_count*n_enc_state*ggml_type_size(GGML_TYPE_F32);
662
663 // cross_attn_token_to_img
664 ctx_size += tfm_layers_count*qkv_count*n_enc_state*(n_enc_state/2)*ggml_type_size(GGML_TYPE_F16);
665 ctx_size += tfm_layers_count*qkv_count*(n_enc_state/2)* ggml_type_size(GGML_TYPE_F32);
666 ctx_size += tfm_layers_count*n_enc_state* ggml_type_size(GGML_TYPE_F32);
667
668 // mlp
669 ctx_size += tfm_layers_count*8*n_enc_out_chans*n_enc_out_chans*ggml_type_size(GGML_TYPE_F16);
670 ctx_size += tfm_layers_count*8*n_enc_out_chans* ggml_type_size(GGML_TYPE_F32);
671 ctx_size += tfm_layers_count*n_enc_out_chans*8*n_enc_out_chans*ggml_type_size(GGML_TYPE_F16);
672 ctx_size += tfm_layers_count*n_enc_out_chans* ggml_type_size(GGML_TYPE_F32);
673
674 // cross_attn_img_to_token
675 ctx_size += tfm_layers_count*qkv_count*n_enc_state*(n_enc_state/2)*ggml_type_size(GGML_TYPE_F16);
676 ctx_size += tfm_layers_count*qkv_count*(n_enc_state/2)* ggml_type_size(GGML_TYPE_F32);
677 ctx_size += tfm_layers_count*n_enc_state* ggml_type_size(GGML_TYPE_F32);
678
679 // transformer_final_attn_token_to_img
680 ctx_size += qkv_count*n_enc_state*(n_enc_state/2)*ggml_type_size(GGML_TYPE_F16);
681 ctx_size += qkv_count*(n_enc_state/2)* ggml_type_size(GGML_TYPE_F32);
682 ctx_size += n_enc_state* ggml_type_size(GGML_TYPE_F32);
683
684 // transformer_norm_final
685 ctx_size += norm_count*n_enc_state*ggml_type_size(GGML_TYPE_F32);
686 ctx_size += norm_count*n_enc_state*ggml_type_size(GGML_TYPE_F32);
687
688 // output_upscaling
689 ctx_size += n_enc_out_chans*n_img_embd*2*2*ggml_type_size(GGML_TYPE_F16);
690 ctx_size += 3*n_img_embd* ggml_type_size(GGML_TYPE_F32);
691 ctx_size += n_enc_out_chans*n_img_embd*(n_img_embd/2)*2*2*ggml_type_size(GGML_TYPE_F16);
692 ctx_size += (n_img_embd/2)* ggml_type_size(GGML_TYPE_F32);
693
694 // output_hypernetworks_mlps
695 ctx_size += n_hypernet_mpls_count*2*n_enc_out_chans*n_enc_out_chans*ggml_type_size(GGML_TYPE_F16);
696 ctx_size += n_hypernet_mpls_count*2*n_enc_out_chans* ggml_type_size(GGML_TYPE_F32);
697 ctx_size += n_hypernet_mpls_count*n_enc_out_chans*(n_img_embd/2)*ggml_type_size(GGML_TYPE_F16);
698 ctx_size += n_hypernet_mpls_count*(n_img_embd/2)* ggml_type_size(GGML_TYPE_F32);
699
700 // iou_prediction_head
701 ctx_size += 2*n_enc_out_chans*n_enc_out_chans*ggml_type_size(GGML_TYPE_F16);
702 ctx_size += 2*n_enc_out_chans* ggml_type_size(GGML_TYPE_F32);
703 ctx_size += n_pt_embd*n_enc_out_chans*ggml_type_size(GGML_TYPE_F16);
704 ctx_size += n_pt_embd* ggml_type_size(GGML_TYPE_F32);
705
706 // iou_token_w
707 ctx_size += n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
708
709 // mask_tokens_w
710 ctx_size += n_pt_embd*n_enc_out_chans*ggml_type_size(GGML_TYPE_F32);
711 }
712 }
713 fprintf(stderr, "%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
714
715 return ctx_size;
716 }();
717
718 // create the ggml context
719 {
720 struct ggml_init_params params = {
721 /*.mem_size =*/ ctx_size,
722 /*.mem_buffer =*/ NULL,
723 /*.no_alloc =*/ false,
724 };
725
726 ctx = ggml_init(params);
727 if (!ctx) {
728 fprintf(stderr, "%s: ggml_init() failed\n", __func__);
729 return false;
730 }
731 }
732
733 // prepare memory for the weights
734 {
735 const auto & hparams = model.hparams;
736
737 const int32_t n_enc_state = hparams.n_enc_state;
738 const int32_t n_enc_layer = hparams.n_enc_layer;
739 const int32_t n_enc_head_dim = hparams.n_enc_head_dim();
740 const int32_t n_enc_out_chans = hparams.n_enc_out_chans;
741 const int32_t n_pt_embd = hparams.n_pt_embd;
742
743 const int32_t n_img_embd = hparams.n_img_embd();
744 const int32_t n_window_size = hparams.n_window_size();
745 const int32_t n_patch_size = hparams.n_patch_size();
746
747 model.enc_img.layers.resize(n_enc_layer);
748
749 // image encoder
750 {
751 auto & enc = model.enc_img;
752
753 enc.pe = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, n_enc_state, n_img_embd, n_img_embd, 1);
754
755 enc.proj_w = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_patch_size, n_patch_size, 3, n_enc_state);
756 enc.proj_b = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 1, 1, n_enc_state);
757
758 enc.neck_conv_0 = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 1, 1, n_enc_state, n_enc_out_chans);
759 enc.neck_conv_1 = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 3, 3, n_enc_out_chans, n_enc_out_chans);
760
761 enc.neck_norm_0_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
762 enc.neck_norm_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
763
764 enc.neck_norm_1_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
765 enc.neck_norm_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
766
767 model.tensors["image_encoder.pos_embed"] = enc.pe;
768
769 model.tensors["image_encoder.patch_embed.proj.weight"] = enc.proj_w;
770 model.tensors["image_encoder.patch_embed.proj.bias"] = enc.proj_b;
771
772 model.tensors["image_encoder.neck.0.weight"] = enc.neck_conv_0;
773 model.tensors["image_encoder.neck.2.weight"] = enc.neck_conv_1;
774
775 model.tensors["image_encoder.neck.1.weight"] = enc.neck_norm_0_w;
776 model.tensors["image_encoder.neck.1.bias"] = enc.neck_norm_0_b;
777
778 model.tensors["image_encoder.neck.3.weight"] = enc.neck_norm_1_w;
779 model.tensors["image_encoder.neck.3.bias"] = enc.neck_norm_1_b;
780
781 for (int i = 0; i < n_enc_layer; ++i) {
782 auto & layer = enc.layers[i];
783
784 layer.norm1_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_state);
785 layer.norm1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_state);
786
787 if (hparams.is_global_attn(i)) {
788 layer.rel_pos_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_head_dim, 2*n_img_embd - 1);
789 layer.rel_pos_h = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_head_dim, 2*n_img_embd - 1);
790 } else {
791 layer.rel_pos_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_head_dim, 2*n_window_size - 1);
792 layer.rel_pos_h = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_head_dim, 2*n_window_size - 1);
793 }
794
795 layer.qkv_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_state, 3*n_enc_state);
796 layer.qkv_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 3*n_enc_state);
797
798 layer.proj_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_state, n_enc_state);
799 layer.proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_state);
800
801 layer.norm2_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_state);
802 layer.norm2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_state);
803
804 layer.mlp_lin1_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_state, 4*n_enc_state);
805 layer.mlp_lin1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_enc_state);
806
807 layer.mlp_lin2_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, 4*n_enc_state, n_enc_state);
808 layer.mlp_lin2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_state);
809
810 model.tensors["image_encoder.blocks." + std::to_string(i) + ".norm1.weight"] = layer.norm1_w;
811 model.tensors["image_encoder.blocks." + std::to_string(i) + ".norm1.bias"] = layer.norm1_b;
812
813 model.tensors["image_encoder.blocks." + std::to_string(i) + ".attn.rel_pos_w"] = layer.rel_pos_w;
814 model.tensors["image_encoder.blocks." + std::to_string(i) + ".attn.rel_pos_h"] = layer.rel_pos_h;
815
816 model.tensors["image_encoder.blocks." + std::to_string(i) + ".attn.qkv.weight"] = layer.qkv_w;
817 model.tensors["image_encoder.blocks." + std::to_string(i) + ".attn.qkv.bias"] = layer.qkv_b;
818
819 model.tensors["image_encoder.blocks." + std::to_string(i) + ".attn.proj.weight"] = layer.proj_w;
820 model.tensors["image_encoder.blocks." + std::to_string(i) + ".attn.proj.bias"] = layer.proj_b;
821
822 model.tensors["image_encoder.blocks." + std::to_string(i) + ".norm2.weight"] = layer.norm2_w;
823 model.tensors["image_encoder.blocks." + std::to_string(i) + ".norm2.bias"] = layer.norm2_b;
824
825 model.tensors["image_encoder.blocks." + std::to_string(i) + ".mlp.lin1.weight"] = layer.mlp_lin1_w;
826 model.tensors["image_encoder.blocks." + std::to_string(i) + ".mlp.lin1.bias"] = layer.mlp_lin1_b;
827
828 model.tensors["image_encoder.blocks." + std::to_string(i) + ".mlp.lin2.weight"] = layer.mlp_lin2_w;
829 model.tensors["image_encoder.blocks." + std::to_string(i) + ".mlp.lin2.bias"] = layer.mlp_lin2_b;
830 }
831 }
832
833 // prompt encoder
834 {
835 auto & enc = model.enc_prompt;
836
837 enc.pe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_enc_out_chans/2, 2);
838
839 enc.not_a_pt_embd_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
840 enc.no_mask_embd_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
841
842 model.tensors["prompt_encoder.pe_layer.positional_encoding_gaussian_matrix"] = enc.pe;
843 model.tensors["prompt_encoder.not_a_point_embed.weight"] = enc.not_a_pt_embd_w;
844 model.tensors["prompt_encoder.no_mask_embed.weight"] = enc.no_mask_embd_w;
845
846 enc.pt_embd.resize(n_pt_embd);
847 for (int i = 0; i < n_pt_embd; i++) {
848 enc.pt_embd[i] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
849
850 model.tensors["prompt_encoder.point_embeddings." + std::to_string(i) + ".weight"] = enc.pt_embd[i];
851 }
852 }
853
854 // mask decoder
855 {
856 auto & dec = model.dec;
857 auto & tfm_layers = dec.transformer_layers;
858
859 const int tfm_layers_count = 2;
860 tfm_layers.resize(tfm_layers_count);
861 for (int i = 0; i < tfm_layers_count; ++i) {
862 auto& l = tfm_layers[i];
863 l.self_attn.q_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
864 l.self_attn.q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
865 l.self_attn.k_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
866 l.self_attn.k_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
867 l.self_attn.v_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
868 l.self_attn.v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
869 l.self_attn.out_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
870 l.self_attn.out_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
871
872 l.norm1_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
873 l.norm1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
874
875 l.cross_attn_token_to_img.q_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
876 l.cross_attn_token_to_img.q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
877 l.cross_attn_token_to_img.k_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
878 l.cross_attn_token_to_img.k_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
879 l.cross_attn_token_to_img.v_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
880 l.cross_attn_token_to_img.v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
881 l.cross_attn_token_to_img.out_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans/2, n_enc_out_chans);
882 l.cross_attn_token_to_img.out_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
883
884 l.norm2_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
885 l.norm2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
886
887 l.mlp_lin1_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, 8*n_enc_out_chans);
888 l.mlp_lin1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 8*n_enc_out_chans);
889 l.mlp_lin2_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, 8*n_enc_out_chans, n_enc_out_chans);
890 l.mlp_lin2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
891
892 l.norm3_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
893 l.norm3_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
894
895 l.norm4_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
896 l.norm4_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
897
898 l.cross_attn_img_to_token.q_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
899 l.cross_attn_img_to_token.q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
900 l.cross_attn_img_to_token.k_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
901 l.cross_attn_img_to_token.k_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
902 l.cross_attn_img_to_token.v_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
903 l.cross_attn_img_to_token.v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
904 l.cross_attn_img_to_token.out_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans/2, n_enc_out_chans);
905 l.cross_attn_img_to_token.out_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
906
907 const auto prefix = "mask_decoder.transformer.layers." + std::to_string(i) + ".";
908 model.tensors[prefix + "self_attn.q_proj.weight"] = l.self_attn.q_w;
909 model.tensors[prefix + "self_attn.q_proj.bias"] = l.self_attn.q_b;
910 model.tensors[prefix + "self_attn.k_proj.weight"] = l.self_attn.k_w;
911 model.tensors[prefix + "self_attn.k_proj.bias"] = l.self_attn.k_b;
912 model.tensors[prefix + "self_attn.v_proj.weight"] = l.self_attn.v_w;
913 model.tensors[prefix + "self_attn.v_proj.bias"] = l.self_attn.v_b;
914 model.tensors[prefix + "self_attn.out_proj.weight"] = l.self_attn.out_w;
915 model.tensors[prefix + "self_attn.out_proj.bias"] = l.self_attn.out_b;
916
917 model.tensors[prefix + "norm1.weight"] = l.norm1_w;
918 model.tensors[prefix + "norm1.bias"] = l.norm1_b;
919
920 model.tensors[prefix + "cross_attn_token_to_image.q_proj.weight"] = l.cross_attn_token_to_img.q_w;
921 model.tensors[prefix + "cross_attn_token_to_image.q_proj.bias"] = l.cross_attn_token_to_img.q_b;
922 model.tensors[prefix + "cross_attn_token_to_image.k_proj.weight"] = l.cross_attn_token_to_img.k_w;
923 model.tensors[prefix + "cross_attn_token_to_image.k_proj.bias"] = l.cross_attn_token_to_img.k_b;
924 model.tensors[prefix + "cross_attn_token_to_image.v_proj.weight"] = l.cross_attn_token_to_img.v_w;
925 model.tensors[prefix + "cross_attn_token_to_image.v_proj.bias"] = l.cross_attn_token_to_img.v_b;
926 model.tensors[prefix + "cross_attn_token_to_image.out_proj.weight"] = l.cross_attn_token_to_img.out_w;
927 model.tensors[prefix + "cross_attn_token_to_image.out_proj.bias"] = l.cross_attn_token_to_img.out_b;
928
929 model.tensors[prefix + "norm2.weight"] = l.norm2_w;
930 model.tensors[prefix + "norm2.bias"] = l.norm2_b;
931
932 model.tensors[prefix + "mlp.lin1.weight"] = l.mlp_lin1_w;
933 model.tensors[prefix + "mlp.lin1.bias"] = l.mlp_lin1_b;
934 model.tensors[prefix + "mlp.lin2.weight"] = l.mlp_lin2_w;
935 model.tensors[prefix + "mlp.lin2.bias"] = l.mlp_lin2_b;
936
937 model.tensors[prefix + "norm3.weight"] = l.norm3_w;
938 model.tensors[prefix + "norm3.bias"] = l.norm3_b;
939 model.tensors[prefix + "norm4.weight"] = l.norm4_w;
940 model.tensors[prefix + "norm4.bias"] = l.norm4_b;
941
942 model.tensors[prefix + "cross_attn_image_to_token.q_proj.weight"] = l.cross_attn_img_to_token.q_w;
943 model.tensors[prefix + "cross_attn_image_to_token.q_proj.bias"] = l.cross_attn_img_to_token.q_b;
944 model.tensors[prefix + "cross_attn_image_to_token.k_proj.weight"] = l.cross_attn_img_to_token.k_w;
945 model.tensors[prefix + "cross_attn_image_to_token.k_proj.bias"] = l.cross_attn_img_to_token.k_b;
946 model.tensors[prefix + "cross_attn_image_to_token.v_proj.weight"] = l.cross_attn_img_to_token.v_w;
947 model.tensors[prefix + "cross_attn_image_to_token.v_proj.bias"] = l.cross_attn_img_to_token.v_b;
948 model.tensors[prefix + "cross_attn_image_to_token.out_proj.weight"] = l.cross_attn_img_to_token.out_w;
949 model.tensors[prefix + "cross_attn_image_to_token.out_proj.bias"] = l.cross_attn_img_to_token.out_b;
950 }
951
952 dec.transformer_final_attn_token_to_img.q_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
953 dec.transformer_final_attn_token_to_img.q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
954 dec.transformer_final_attn_token_to_img.k_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
955 dec.transformer_final_attn_token_to_img.k_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
956 dec.transformer_final_attn_token_to_img.v_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans/2);
957 dec.transformer_final_attn_token_to_img.v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans/2);
958 dec.transformer_final_attn_token_to_img.out_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans/2, n_enc_out_chans);
959 dec.transformer_final_attn_token_to_img.out_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
960
961 model.tensors["mask_decoder.transformer.final_attn_token_to_image.q_proj.weight"] = dec.transformer_final_attn_token_to_img.q_w;
962 model.tensors["mask_decoder.transformer.final_attn_token_to_image.q_proj.bias"] = dec.transformer_final_attn_token_to_img.q_b;
963 model.tensors["mask_decoder.transformer.final_attn_token_to_image.k_proj.weight"] = dec.transformer_final_attn_token_to_img.k_w;
964 model.tensors["mask_decoder.transformer.final_attn_token_to_image.k_proj.bias"] = dec.transformer_final_attn_token_to_img.k_b;
965 model.tensors["mask_decoder.transformer.final_attn_token_to_image.v_proj.weight"] = dec.transformer_final_attn_token_to_img.v_w;
966 model.tensors["mask_decoder.transformer.final_attn_token_to_image.v_proj.bias"] = dec.transformer_final_attn_token_to_img.v_b;
967 model.tensors["mask_decoder.transformer.final_attn_token_to_image.out_proj.weight"] = dec.transformer_final_attn_token_to_img.out_w;
968 model.tensors["mask_decoder.transformer.final_attn_token_to_image.out_proj.bias"] = dec.transformer_final_attn_token_to_img.out_b;
969
970 dec.transformer_norm_final_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
971 dec.transformer_norm_final_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
972
973 model.tensors["mask_decoder.transformer.norm_final_attn.weight"] = dec.transformer_norm_final_w;
974 model.tensors["mask_decoder.transformer.norm_final_attn.bias"] = dec.transformer_norm_final_b;
975
976 dec.output_upscaling_0_w = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 2, 2, n_img_embd, n_enc_out_chans);
977 dec.output_upscaling_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_img_embd);
978 dec.output_upscaling_1_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_img_embd);
979 dec.output_upscaling_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_img_embd);
980 dec.output_upscaling_3_w = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 2, 2, n_img_embd/2, n_img_embd);
981 dec.output_upscaling_3_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_img_embd/2);
982
983 model.tensors["mask_decoder.output_upscaling.0.weight"] = dec.output_upscaling_0_w;
984 model.tensors["mask_decoder.output_upscaling.0.bias"] = dec.output_upscaling_0_b;
985 model.tensors["mask_decoder.output_upscaling.1.weight"] = dec.output_upscaling_1_w;
986 model.tensors["mask_decoder.output_upscaling.1.bias"] = dec.output_upscaling_1_b;
987 model.tensors["mask_decoder.output_upscaling.3.weight"] = dec.output_upscaling_3_w;
988 model.tensors["mask_decoder.output_upscaling.3.bias"] = dec.output_upscaling_3_b;
989
990 const int n_hypernet_mpls_count = 4;
991 dec.output_hypernet_mlps.resize(n_hypernet_mpls_count);
992 for (int i = 0; i < n_hypernet_mpls_count; ++i) {
993 auto& mlp = dec.output_hypernet_mlps[i];
994
995 mlp.w_0 = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
996 mlp.b_0 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
997 mlp.w_1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
998 mlp.b_1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
999 mlp.w_2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_img_embd/2);
1000 mlp.b_2 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_img_embd/2);
1001
1002 const auto prefix = "mask_decoder.output_hypernetworks_mlps." + std::to_string(i) + ".";
1003 model.tensors[prefix + "layers.0.weight"] = mlp.w_0;
1004 model.tensors[prefix + "layers.0.bias"] = mlp.b_0;
1005 model.tensors[prefix + "layers.1.weight"] = mlp.w_1;
1006 model.tensors[prefix + "layers.1.bias"] = mlp.b_1;
1007 model.tensors[prefix + "layers.2.weight"] = mlp.w_2;
1008 model.tensors[prefix + "layers.2.bias"] = mlp.b_2;
1009 }
1010
1011 dec.iou_prediction_head_0_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
1012 dec.iou_prediction_head_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
1013 dec.iou_prediction_head_1_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_enc_out_chans);
1014 dec.iou_prediction_head_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_enc_out_chans);
1015 dec.iou_prediction_head_2_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, n_enc_out_chans, n_pt_embd);
1016 dec.iou_prediction_head_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_pt_embd);
1017
1018 dec.iou_token_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_enc_out_chans, 1);
1019 dec.mask_tokens_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_enc_out_chans, n_pt_embd);
1020
1021 model.tensors["mask_decoder.iou_prediction_head.layers.0.weight"] = dec.iou_prediction_head_0_w;
1022 model.tensors["mask_decoder.iou_prediction_head.layers.0.bias"] = dec.iou_prediction_head_0_b;
1023 model.tensors["mask_decoder.iou_prediction_head.layers.1.weight"] = dec.iou_prediction_head_1_w;
1024 model.tensors["mask_decoder.iou_prediction_head.layers.1.bias"] = dec.iou_prediction_head_1_b;
1025 model.tensors["mask_decoder.iou_prediction_head.layers.2.weight"] = dec.iou_prediction_head_2_w;
1026 model.tensors["mask_decoder.iou_prediction_head.layers.2.bias"] = dec.iou_prediction_head_2_b;
1027
1028 model.tensors["mask_decoder.iou_token.weight"] = dec.iou_token_w;
1029 model.tensors["mask_decoder.mask_tokens.weight"] = dec.mask_tokens_w;
1030 }
1031 }
1032
1033 // load weights
1034 {
1035 int n_tensors = 0;
1036 size_t total_size = 0;
1037
1038 fprintf(stderr, "%s: ", __func__);
1039
1040 while (true) {
1041 int32_t n_dims;
1042 int32_t length;
1043 int32_t ftype;
1044
1045 fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
1046 fin.read(reinterpret_cast<char *>(&length), sizeof(length));
1047 fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
1048
1049 if (fin.eof()) {
1050 break;
1051 }
1052
1053 int64_t nelements = 1;
1054 int64_t ne[4] = { 1, 1, 1, 1 };
1055 for (int i = 0; i < n_dims; ++i) {
1056 int32_t ne_cur;
1057 fin.read(reinterpret_cast<char *>(&ne_cur), sizeof(ne_cur));
1058 ne[i] = ne_cur;
1059 nelements *= ne[i];
1060 }
1061
1062 std::string name(length, 0);
1063 fin.read(&name[0], length);
1064
1065 if (model.tensors.find(name.data()) == model.tensors.end()) {
1066 fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
1067 return false;
1068 }
1069
1070 auto tensor = model.tensors[name.data()];
1071 //printf("ne0 = %jd, ne1 = %jd, ne2 = %jd, ne3 = %jd\n", ne[0], ne[1], ne[2], ne[3]);
1072
1073 if (ggml_nelements(tensor) != nelements) {
1074 fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %d, expected %d\n",
1075 __func__, name.data(), (int) nelements, (int) ggml_nelements(tensor));
1076 return false;
1077 }
1078
1079 if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1] || tensor->ne[2] != ne[2] || tensor->ne[3] != ne[3]) {
1080 fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d, %d, %d], expected [%d, %d, %d, %d]\n",
1081 __func__, name.data(),
1082 (int) ne[0], (int) ne[1], (int) ne[2], (int) ne[3],
1083 (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2], (int) tensor->ne[3]);
1084 return false;
1085 }
1086
1087 size_t bpe = 0;
1088
1089 switch (ftype) {
1090 case 0: bpe = ggml_type_size(GGML_TYPE_F32); break;
1091 case 1: bpe = ggml_type_size(GGML_TYPE_F16); break;
1092 case 2: bpe = ggml_type_size(GGML_TYPE_Q4_0); assert(ne[0] % 64 == 0); break;
1093 case 3: bpe = ggml_type_size(GGML_TYPE_Q4_1); assert(ne[0] % 64 == 0); break;
1094 default:
1095 {
1096 fprintf(stderr, "%s: unknown ftype %d in model file\n", __func__, ftype);
1097 return false;
1098 }
1099 };
1100
1101 if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
1102 fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
1103 __func__, name.data(), ggml_nbytes(tensor), (size_t) nelements*bpe);
1104 return false;
1105 }
1106
1107 fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
1108
1109 total_size += ggml_nbytes(tensor);
1110 if (++n_tensors % 8 == 0) {
1111 fprintf(stderr, ".");
1112 fflush(stdout);
1113 }
1114 }
1115
1116 if (n_tensors != int(model.tensors.size())) {
1117 fprintf(stderr, "%s: model file has %d tensors, but %d tensors were expected\n", __func__, n_tensors, (int) model.tensors.size());
1118 return false;
1119 }
1120
1121 fprintf(stderr, " done\n");
1122
1123 fprintf(stderr, "%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors);
1124 }
1125
1126 fin.close();
1127
1128 return true;
1129}
1130
1131struct ggml_tensor * sam_fill_dense_pe(
1132 const sam_model & model,
1133 struct ggml_context * ctx0,
1134 struct ggml_cgraph * gf,
1135 sam_state & state) {
1136 const auto & hparams = model.hparams;
1137 const auto & enc = model.enc_prompt;
1138
1139
1140 const int32_t n_img_embd = hparams.n_img_embd();
1141 struct ggml_tensor * xy_embed_stacked = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 2, n_img_embd, n_img_embd);
1142 ggml_set_name(xy_embed_stacked, "xy_embed_stacked");
1143 ggml_set_input(xy_embed_stacked);
1144
1145 struct ggml_tensor * cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, enc.pe)), xy_embed_stacked);
1146
1147 cur = ggml_scale(ctx0, cur, float(2.0*M_PI));
1148
1149 // concat
1150 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L192
1151 {
1152 struct ggml_tensor * t_sin = ggml_map_custom1(ctx0, cur, ggml_sam_sin, GGML_N_TASKS_MAX, NULL);
1153 struct ggml_tensor * t_cos = ggml_map_custom1(ctx0, cur, ggml_sam_cos, GGML_N_TASKS_MAX, NULL);
1154
1155 cur = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, t_sin->ne[0] + t_cos->ne[0], cur->ne[1], cur->ne[2]);
1156
1157 ggml_build_forward_expand(gf, ggml_cpy(ctx0, t_sin, ggml_view_3d(ctx0, cur, t_sin->ne[0], t_sin->ne[1], t_sin->ne[2], cur->nb[1], cur->nb[2], 0)));
1158 ggml_build_forward_expand(gf, ggml_cpy(ctx0, t_cos, ggml_view_3d(ctx0, cur, t_sin->ne[0], t_sin->ne[1], t_sin->ne[2], cur->nb[1], cur->nb[2], t_sin->nb[1])));
1159 }
1160
1161 struct ggml_tensor * pe_img_dense = ggml_cont(ctx0, ggml_permute(ctx0, cur, 2, 0, 1, 3));
1162 ggml_build_forward_expand(gf, pe_img_dense);
1163
1164 return pe_img_dense;
1165}
1166
1167struct ggml_tensor* sam_layer_norm_2d(
1168 struct ggml_context * ctx0,
1169 struct ggml_tensor * layer,
1170 int n_channels,
1171 struct ggml_tensor * w,
1172 struct ggml_tensor * b,
1173 float eps) {
1174 // LayerNorm2d
1175 // normalize along channel dimmension
1176 // TODO: better implementation
1177 layer = ggml_permute(ctx0,
1178 ggml_norm(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, layer, 1, 2, 0, 3)), eps),
1179 2, 0, 1, 3);
1180
1181 layer = ggml_add(ctx0,
1182 ggml_mul(ctx0,
1183 ggml_repeat(ctx0, ggml_reshape_3d(ctx0, w, 1, 1, n_channels), layer),
1184 layer),
1185 ggml_repeat(ctx0, ggml_reshape_3d(ctx0, b, 1, 1, n_channels), layer));
1186
1187 return layer;
1188}
1189
1190struct ggml_cgraph * sam_encode_image(
1191 const sam_model & model,
1192 sam_state & state,
1193 const sam_image_f32 & img) {
1194
1195 const auto & hparams = model.hparams;
1196 const auto & enc = model.enc_img;
1197
1198 const int32_t n_enc_state = hparams.n_enc_state;
1199 const int32_t n_enc_layer = hparams.n_enc_layer;
1200 const int32_t n_enc_head = hparams.n_enc_head;
1201 const int32_t n_enc_head_dim = hparams.n_enc_head_dim();
1202 const int32_t n_enc_out_chans = hparams.n_enc_out_chans;
1203 const int32_t n_img_size = hparams.n_img_size();
1204 const int32_t n_window_size = hparams.n_window_size();
1205
1206 struct ggml_init_params ggml_params = {
1207 /*.mem_size =*/ state.buf_compute_img_enc.size(),
1208 /*.mem_buffer =*/ state.buf_compute_img_enc.data(),
1209 /*.no_alloc =*/ true, // skip allocating as we use ggml_alloc to allocate exact memory requirements
1210 };
1211
1212 struct ggml_context * ctx0 = ggml_init(ggml_params);
1213 struct ggml_cgraph * gf = ggml_new_graph(ctx0);
1214
1215 struct ggml_tensor * inp = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_img_size, n_img_size, 3, 1);
1216 ggml_set_name(inp, "inp");
1217 ggml_set_input(inp);
1218
1219 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L392
1220 struct ggml_tensor * cur = ggml_conv_2d_sk_p0(ctx0, enc.proj_w, inp);
1221 cur = ggml_add_inplace(ctx0,
1222 cur,
1223 ggml_repeat(ctx0, enc.proj_b, cur));
1224
1225 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L394
1226 // keep in F32
1227 cur = ggml_cont(ctx0,
1228 ggml_permute(ctx0, cur, 1, 2, 0, 3));
1229
1230 // convert to F16
1231 //cur = ggml_cpy(ctx0,
1232 // ggml_permute(ctx0, cur, 1, 2, 0, 3),
1233 // ggml_new_tensor_3d(ctx0, GGML_TYPE_F16, n_enc_state, n_img_embd, n_img_embd));
1234
1235 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L108-L109
1236 cur = ggml_add_inplace(ctx0, cur, enc.pe);
1237
1238 struct ggml_tensor * inpL = cur;
1239
1240 for (int il = 0; il < n_enc_layer; ++il) {
1241 const auto & layer = enc.layers[il];
1242
1243 // norm
1244 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L168
1245 {
1246 cur = ggml_norm(ctx0, inpL, hparams.eps);
1247
1248 // cur = ln_0_w*cur + ln_0_b
1249 cur = ggml_mul(ctx0, cur, layer.norm1_w);
1250 cur = ggml_add_inplace(ctx0, cur, layer.norm1_b);
1251 }
1252
1253 const int64_t w0 = cur->ne[1];
1254 const int64_t h0 = cur->ne[2];
1255
1256 if (hparams.is_global_attn(il) == false) {
1257 // local attention layer - apply window partition
1258 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L169-L172
1259 cur = ggml_win_part(ctx0, cur, n_window_size);
1260 }
1261
1262 const int64_t W = cur->ne[1];
1263 const int64_t H = cur->ne[2];
1264
1265 // self-attention
1266 {
1267 cur = ggml_mul_mat(ctx0, layer.qkv_w, cur);
1268 cur = ggml_add_inplace(ctx0, cur, layer.qkv_b);
1269
1270 // qkv is stored as three n_enc_state-wide segments (q, k, v) along dim 0, each
1271 // holding n_enc_head heads of n_enc_head_dim values - slice them as strided views
1272 // instead of materializing the split (same approach as clip.cpp in llama.cpp)
1273 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L225-L229
1274 const int B = cur->ne[3];
1275
1276 const size_t nb_head = n_enc_head_dim * cur->nb[0]; // stride between heads inside a segment
1277 const size_t nb_seg = n_enc_state * cur->nb[0]; // stride between the q, k and v segments
1278
1279 struct ggml_tensor * Q = ggml_view_4d(ctx0, cur, n_enc_head_dim, W*H, n_enc_head, B, cur->nb[1], nb_head, cur->nb[3], 0*nb_seg);
1280 struct ggml_tensor * K = ggml_view_4d(ctx0, cur, n_enc_head_dim, W*H, n_enc_head, B, cur->nb[1], nb_head, cur->nb[3], 1*nb_seg);
1281 struct ggml_tensor * V = ggml_view_4d(ctx0, cur, n_enc_head_dim, W*H, n_enc_head, B, cur->nb[1], nb_head, cur->nb[3], 2*nb_seg);
1282
1283 // ggml_mul_mat consumes the strided K directly
1284 struct ggml_tensor * KQ = ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, K, Q), W*H, W*H, B*n_enc_head);
1285
1286 // rel_pos needs a contiguous q; V must be transposed for the second mul_mat
1287 Q = ggml_reshape_3d(ctx0, ggml_cont(ctx0, Q), n_enc_head_dim, W*H, B*n_enc_head);
1288 V = ggml_reshape_3d(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, V, 1, 0, 2, 3)), W*H, n_enc_head_dim, B*n_enc_head);
1289
1290 struct ggml_tensor * KQ_scaled =
1291 ggml_scale_inplace(ctx0,
1292 KQ,
1293 1.0f/sqrtf(n_enc_head_dim));
1294
1295 struct ggml_tensor * rw = ggml_get_rel_pos(ctx0, layer.rel_pos_w, W, W);
1296 struct ggml_tensor * rh = ggml_get_rel_pos(ctx0, layer.rel_pos_h, H, H);
1297
1298 struct ggml_tensor * q_r = ggml_reshape_4d(ctx0, Q, n_enc_head_dim, W, H, B*n_enc_head);
1299
1300 struct ggml_tensor * rel_w = ggml_cont(ctx0, ggml_permute(ctx0,
1301 ggml_mul_mat(ctx0,
1302 rw,
1303 ggml_cont(ctx0, ggml_permute(ctx0, q_r, 0, 2, 1, 3))),
1304 0, 2, 1, 3));
1305 struct ggml_tensor * rel_h = ggml_mul_mat(ctx0, rh, q_r);
1306
1307 struct ggml_tensor * attn = ggml_add_rel_pos_inplace(ctx0, KQ_scaled, rel_w, rel_h);
1308
1309 struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, attn);
1310
1311 struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
1312
1313 cur =
1314 ggml_reshape_4d(ctx0,
1315 ggml_cont(ctx0,
1316 ggml_permute(ctx0,
1317 ggml_reshape_4d(ctx0, KQV, n_enc_head_dim, W*H, n_enc_head, B),
1318 0, 2, 1, 3)),
1319 n_enc_state, W, H, B);
1320
1321 cur = ggml_mul_mat(ctx0, layer.proj_w, cur);
1322 cur = ggml_add_inplace(ctx0, cur, layer.proj_b);
1323 }
1324
1325 if (hparams.is_global_attn(il) == false) {
1326 // local attention layer - reverse window partition
1327 cur = ggml_win_unpart(ctx0, cur, w0, h0, n_window_size);
1328 }
1329
1330 cur = ggml_add_inplace(ctx0, cur, inpL);
1331
1332 struct ggml_tensor * inpFF = cur;
1333
1334 // feed-forward network
1335 {
1336 // norm
1337 {
1338 cur = ggml_norm(ctx0, inpFF, hparams.eps);
1339
1340 // cur = mlp_ln_w*cur + mlp_ln_b
1341 cur = ggml_mul(ctx0, cur, layer.norm2_w);
1342 cur = ggml_add_inplace(ctx0, cur, layer.norm2_b);
1343 }
1344
1345 // fully connected
1346 cur = ggml_mul_mat(ctx0, layer.mlp_lin1_w, cur);
1347 cur = ggml_add_inplace(ctx0, cur, layer.mlp_lin1_b);
1348
1349 // GELU activation
1350 cur = ggml_gelu(ctx0, cur);
1351
1352 // projection
1353 cur = ggml_mul_mat(ctx0, layer.mlp_lin2_w, cur);
1354 cur = ggml_add_inplace(ctx0, cur, layer.mlp_lin2_b);
1355 }
1356
1357 inpL = ggml_add(ctx0, cur, inpFF);
1358 }
1359
1360 cur = ggml_cont(ctx0, ggml_permute(ctx0, inpL, 2, 0, 1, 3));
1361
1362 cur = ggml_conv_2d_sk_p0(ctx0, enc.neck_conv_0, cur);
1363
1364 cur = sam_layer_norm_2d(ctx0, cur, n_enc_out_chans, enc.neck_norm_0_w, enc.neck_norm_0_b, hparams.eps);
1365
1366 cur = ggml_conv_2d_s1_ph(ctx0, enc.neck_conv_1, cur);
1367
1368 cur = sam_layer_norm_2d(ctx0, cur, n_enc_out_chans, enc.neck_norm_1_w, enc.neck_norm_1_b, hparams.eps);
1369
1370 cur = ggml_cpy(ctx0, cur, state.embd_img);
1371
1372 ggml_build_forward_expand(gf, cur);
1373 ggml_disconnect_node_from_graph(state.embd_img);
1374
1375 //ggml_graph_print(&gf);
1376
1377 ggml_free(ctx0);
1378
1379 ggml_gallocr_alloc_graph(state.allocr, gf);
1380
1381 {
1382 struct ggml_tensor * inp = ggml_graph_get_tensor(gf, "inp");
1383 float * data = (float *) ggml_get_data(inp);
1384
1385 const int nx = img.nx;
1386 const int ny = img.ny;
1387 const int n = nx*ny;
1388
1389 GGML_ASSERT(nx == n_img_size && ny == n_img_size);
1390
1391 for (int k = 0; k < 3; k++) {
1392 for (int y = 0; y < ny; y++) {
1393 for (int x = 0; x < nx; x++) {
1394 data[k*n + y*nx + x] = img.data[3*(y*nx + x) + k];
1395 }
1396 }
1397 }
1398 }
1399
1400 return gf;
1401}
1402
1403
1404struct prompt_encoder_result {
1405 struct ggml_tensor * embd_prompt_sparse = {};
1406 struct ggml_tensor * embd_prompt_dense = {};
1407};
1408
1409struct ggml_tensor * sam_prompt_encode_pe_encoding(
1410 const sam_encoder_prompt & enc,
1411 struct ggml_context * ctx0,
1412 struct ggml_cgraph * gf,
1413 struct ggml_tensor * coords) {
1414
1415 auto * cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, enc.pe)), coords);
1416 cur = ggml_scale(ctx0, cur, float(2.0*M_PI));
1417
1418 // concat
1419 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L192
1420 {
1421 struct ggml_tensor * t_sin = ggml_map_custom1(ctx0, cur, ggml_sam_sin, GGML_N_TASKS_MAX, NULL);
1422 struct ggml_tensor * t_cos = ggml_map_custom1(ctx0, cur, ggml_sam_cos, GGML_N_TASKS_MAX, NULL);
1423
1424 cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, t_sin->ne[0] + t_cos->ne[0], cur->ne[1]);
1425
1426 ggml_build_forward_expand(gf, ggml_cpy(ctx0, t_sin, ggml_view_2d(ctx0, cur, t_sin->ne[0], t_sin->ne[1], cur->nb[1], 0)));
1427 ggml_build_forward_expand(gf, ggml_cpy(ctx0, t_cos, ggml_view_2d(ctx0, cur, t_sin->ne[0], t_sin->ne[1], cur->nb[1], t_sin->nb[1])));
1428
1429 }
1430 return cur;
1431
1432}
1433// encode a prompt
1434//
1435// - points
1436// - boxes
1437// - masks
1438//
1439// TODO: currently just encode a single point for simplicity
1440//
1441prompt_encoder_result sam_encode_prompt(
1442 const sam_model & model,
1443 struct ggml_context * ctx0,
1444 struct ggml_cgraph * gf,
1445 sam_state & state,
1446 const sam_prompt & prompt) {
1447
1448 const auto & hparams = model.hparams;
1449 const auto & enc = model.enc_prompt;
1450
1451 struct ggml_tensor * inp = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 2, 2);
1452 ggml_set_name(inp, "prompt_input");
1453 ggml_set_input(inp);
1454
1455 auto * embd_prompt_sparse = [&]() -> struct ggml_tensor * {
1456 switch (prompt.prompt_type) {
1457 case SAM_PROMPT_TYPE_POINT: {
1458 // PromptEncoder._embed_points
1459 auto * pt_embd = sam_prompt_encode_pe_encoding(enc, ctx0, gf, inp);
1460
1461 // overwrite label == -1 with not_a_point_embed.weight
1462 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L86
1463 // TODO: extend for multiple points
1464 auto * pt_embd_not = ggml_view_2d(ctx0, pt_embd, pt_embd->ne[0], 1, pt_embd->nb[1], pt_embd->nb[1]);
1465 ggml_build_forward_expand(gf, ggml_cpy(ctx0, enc.not_a_pt_embd_w, pt_embd_not));
1466
1467 // add point_embeddings[1] to label == 1
1468 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L90
1469 auto * pt_embd1 = ggml_view_2d(ctx0, pt_embd, pt_embd->ne[0], 1, pt_embd->nb[1], 0);
1470 ggml_build_forward_expand(gf, ggml_add_inplace(ctx0, pt_embd1, enc.pt_embd[1]));
1471
1472 return pt_embd;
1473 } break;
1474 case SAM_PROMPT_TYPE_BOX: {
1475 // PromptEncoder._embed_boxes
1476 auto * corner_embd = sam_prompt_encode_pe_encoding(enc, ctx0, gf, inp);
1477
1478 // corner_embd[:, 0, :] += self.point_embeddings[2].weight
1479 // corner_embd[:, 1, :] += self.point_embeddings[3].weight
1480 auto * corner0 = ggml_view_2d(
1481 ctx0, corner_embd, corner_embd->ne[0], 1, corner_embd->nb[1], 0);
1482 auto * corner1 = ggml_view_2d(
1483 ctx0, corner_embd, corner_embd->ne[0], 1, corner_embd->nb[1], corner_embd->nb[1]);
1484
1485 ggml_build_forward_expand(gf, ggml_add_inplace(ctx0, corner0, enc.pt_embd[2]));
1486 ggml_build_forward_expand(gf, ggml_add_inplace(ctx0, corner1, enc.pt_embd[3]));
1487
1488 return corner_embd;
1489 } break;
1490 default: {
1491 fprintf(stderr, "%s: unsupported prompt type %d\n", __func__, prompt.prompt_type);
1492 return nullptr;
1493 } break;
1494 }
1495 }();
1496
1497 ggml_build_forward_expand(gf, embd_prompt_sparse);
1498
1499 struct ggml_tensor * embd_prompt_dense = ggml_repeat(ctx0,
1500 ggml_cont(ctx0,
1501 ggml_view_3d(ctx0, enc.no_mask_embd_w,
1502 1, 1, enc.no_mask_embd_w->ne[0], enc.no_mask_embd_w->nb[0], enc.no_mask_embd_w->nb[0], 0)),
1503 ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, hparams.n_img_embd(), hparams.n_img_embd(), hparams.n_enc_out_chans));
1504
1505 ggml_build_forward_expand(gf, embd_prompt_dense);
1506
1507 //printf("used_mem = %zu\n", ggml_used_mem(ctx0));
1508
1509 prompt_encoder_result res;
1510 res.embd_prompt_sparse = embd_prompt_sparse;
1511 res.embd_prompt_dense = embd_prompt_dense;
1512 return res;
1513}
1514
1515struct ggml_tensor* sam_decode_mask_transformer_attn(
1516 const sam_layer_dec_transformer_attn & attn,
1517 struct ggml_tensor * queries,
1518 struct ggml_tensor * keys,
1519 struct ggml_tensor * values,
1520 struct ggml_context * ctx0,
1521 const sam_model & model) {
1522 const auto & hparams = model.hparams;
1523 const int n_head = hparams.n_dec_heads;
1524
1525 struct ggml_tensor * Qcur = {};
1526 struct ggml_tensor * Kcur = {};
1527 struct ggml_tensor * Vcur = {};
1528
1529 Qcur = ggml_mul_mat(ctx0, attn.q_w, queries);
1530 Qcur = ggml_add_inplace(ctx0, Qcur, attn.q_b);
1531
1532 Kcur = ggml_mul_mat(ctx0, attn.k_w, keys);
1533 Kcur = ggml_add_inplace(ctx0, Kcur, attn.k_b);
1534
1535 Vcur = ggml_mul_mat(ctx0, attn.v_w, values);
1536 Vcur = ggml_add_inplace(ctx0, Vcur, attn.v_b);
1537
1538 struct ggml_tensor * Q = {};
1539 struct ggml_tensor * K = {};
1540 struct ggml_tensor * V = {};
1541
1542 Q = ggml_reshape_4d(ctx0, Qcur, Qcur->ne[0]/n_head, n_head, Qcur->ne[1], Qcur->ne[2]);
1543 Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
1544
1545 K = ggml_reshape_4d(ctx0, Kcur, Kcur->ne[0]/n_head, n_head, Kcur->ne[1], Kcur->ne[2]);
1546 K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
1547
1548 V = ggml_reshape_4d(ctx0, Vcur, Vcur->ne[0]/n_head, n_head, Vcur->ne[1], Vcur->ne[2]);
1549 V = ggml_cont(ctx0, ggml_permute(ctx0, V, 0, 2, 1, 3));
1550
1551 // Q * K
1552 struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
1553
1554 struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, 1.0f/sqrt(float(Q->ne[0])));
1555
1556 struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_scaled);
1557
1558 struct ggml_tensor * KQV = ggml_mul_mat(ctx0, KQ_soft_max, ggml_cont(ctx0, ggml_transpose(ctx0, V)));
1559
1560 struct ggml_tensor * KQV_merged = ggml_cont(ctx0, ggml_transpose(ctx0, KQV));
1561 KQV_merged = ggml_cont(ctx0, ggml_permute(ctx0, KQV_merged, 0, 2, 1, 3));
1562 KQV_merged = ggml_reshape_3d(ctx0, KQV_merged, KQV_merged->ne[0]*KQV_merged->ne[1], KQV_merged->ne[2], KQV_merged->ne[3]);
1563 KQV_merged = ggml_mul_mat(ctx0, attn.out_w, KQV_merged);
1564 KQV_merged = ggml_add_inplace(ctx0, KQV_merged, attn.out_b);
1565
1566 return KQV_merged;
1567}
1568
1569struct ggml_tensor * sam_decode_mask_mlp_relu_3(
1570 struct ggml_tensor * in,
1571 struct ggml_tensor * w_0,
1572 struct ggml_tensor * b_0,
1573 struct ggml_tensor * w_1,
1574 struct ggml_tensor * b_1,
1575 struct ggml_tensor * w_2,
1576 struct ggml_tensor * b_2,
1577 struct ggml_context * ctx0) {
1578
1579 struct ggml_tensor * cur = {};
1580 cur = ggml_mul_mat(ctx0, w_0, in);
1581 cur = ggml_add_inplace(ctx0, cur, b_0);
1582
1583 cur = ggml_relu_inplace(ctx0, cur);
1584
1585 cur = ggml_mul_mat(ctx0, w_1, cur);
1586 cur = ggml_add_inplace(ctx0, cur, b_1);
1587
1588 cur = ggml_relu_inplace(ctx0, cur);
1589
1590 cur = ggml_mul_mat(ctx0, w_2, cur);
1591 cur = ggml_add_inplace(ctx0, cur, b_2);
1592
1593 return cur;
1594}
1595
1596bool sam_decode_mask(
1597 const sam_model & model,
1598 const prompt_encoder_result & prompt,
1599 struct ggml_tensor * pe_img,
1600 struct ggml_context * ctx0,
1601 struct ggml_cgraph * gf,
1602 sam_state & state,
1603 const bool multimask_output) {
1604
1605 const auto & hparams = model.hparams;
1606 const auto & dec = model.dec;
1607 const int n_img_embd = hparams.n_img_embd();
1608
1609 struct ggml_tensor * tokens = {};
1610 {
1611 // Concatenate output tokens
1612 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L120
1613 const auto& sparse = prompt.embd_prompt_sparse;
1614
1615 tokens = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, dec.iou_token_w->ne[0], dec.iou_token_w->ne[1] + dec.mask_tokens_w->ne[1] + sparse->ne[1], sparse->ne[2]);
1616
1617 const size_t offsets[3] = { 0, dec.iou_token_w->ne[1]*tokens->nb[1], dec.iou_token_w->ne[1]*tokens->nb[1] + dec.mask_tokens_w->ne[1]*tokens->nb[1] };
1618 ggml_build_forward_expand(gf, ggml_cpy(ctx0, dec.iou_token_w, ggml_view_2d(ctx0, tokens, tokens->ne[0], dec.iou_token_w->ne[1], tokens->nb[1], offsets[0])));
1619 ggml_build_forward_expand(gf, ggml_cpy(ctx0, dec.mask_tokens_w, ggml_view_2d(ctx0, tokens, tokens->ne[0], dec.mask_tokens_w->ne[1], tokens->nb[1], offsets[1])));
1620 ggml_build_forward_expand(gf, ggml_cpy(ctx0, sparse, ggml_view_2d(ctx0, tokens, tokens->ne[0], sparse->ne[1], tokens->nb[1], offsets[2])));
1621 // TODO: Sparse prompt embeddings can have more than one point
1622 }
1623
1624
1625 struct ggml_tensor * src = {};
1626 struct ggml_tensor * pos_src = {};
1627 int srcNE[4] = { 0, 0, 0, 0 };
1628 {
1629 // Expand per-image data in the batch direction to be per-mask
1630 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L125
1631 src = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, state.embd_img->ne[0], state.embd_img->ne[1], state.embd_img->ne[2], tokens->ne[2]);
1632
1633 src = ggml_add(ctx0,
1634 ggml_repeat(ctx0,
1635 state.embd_img,
1636 src),
1637 prompt.embd_prompt_dense);
1638
1639 srcNE[0] = src->ne[0];
1640 srcNE[1] = src->ne[1];
1641 srcNE[2] = src->ne[2];
1642 srcNE[3] = src->ne[3];
1643
1644 // flatten & permute
1645 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L83
1646 src = ggml_cont(ctx0, ggml_permute(ctx0,
1647 ggml_view_3d(ctx0,
1648 src,
1649 src->ne[0]*src->ne[1],
1650 src->ne[2],
1651 src->ne[3],
1652 src->nb[2],
1653 src->nb[3],
1654 0),
1655 1, 0, 2, 3));
1656
1657 pos_src = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, pe_img->ne[0], pe_img->ne[1], pe_img->ne[2], tokens->ne[2]);
1658 pos_src = ggml_repeat(ctx0,
1659 pe_img,
1660 pos_src);
1661
1662 // flatten & permute
1663 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L83
1664 pos_src = ggml_cont(ctx0, ggml_permute(ctx0,
1665 ggml_view_3d(ctx0,
1666 pos_src,
1667 pos_src->ne[0]*pos_src->ne[1],
1668 pos_src->ne[2],
1669 pos_src->ne[3],
1670 pos_src->nb[2],
1671 pos_src->nb[3],
1672 0),
1673 1, 0, 2, 3));
1674 }
1675
1676 struct ggml_tensor * queries = tokens;
1677 struct ggml_tensor * keys = src;
1678 {
1679 // Run the transformer
1680 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L62
1681 for (int i = 0; i < int(model.dec.transformer_layers.size()); ++i) {
1682 const auto& tfm_layer = model.dec.transformer_layers[i];
1683
1684 // Self attention block
1685 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L154
1686 const bool skip_first_layer_pe = i == 0;
1687 if (skip_first_layer_pe) {
1688 queries = sam_decode_mask_transformer_attn(tfm_layer.self_attn, queries, queries, queries, ctx0, model);
1689 }
1690 else {
1691 struct ggml_tensor * q_0 = ggml_add(ctx0, queries, tokens);
1692
1693 struct ggml_tensor * self_attn = sam_decode_mask_transformer_attn(tfm_layer.self_attn, q_0, q_0, queries, ctx0, model);
1694 queries = ggml_add(ctx0, queries, self_attn);
1695 }
1696
1697 queries = ggml_norm(ctx0, queries, hparams.eps_decoder_transformer);
1698 queries = ggml_add_inplace(ctx0,
1699 ggml_mul(ctx0, queries, tfm_layer.norm1_w),
1700 tfm_layer.norm1_b);
1701
1702 // Cross attention block, tokens attending to image embedding
1703 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L163
1704 struct ggml_tensor * q_1 = ggml_add(ctx0, queries, tokens);
1705 struct ggml_tensor * k_1 = ggml_add(ctx0, keys, pos_src);
1706
1707 struct ggml_tensor * cross_attn_token_to_img = sam_decode_mask_transformer_attn(tfm_layer.cross_attn_token_to_img, q_1, k_1, keys, ctx0, model);
1708
1709 queries = ggml_add_inplace(ctx0, queries, cross_attn_token_to_img);
1710 queries = ggml_norm_inplace(ctx0, queries, hparams.eps_decoder_transformer);
1711 queries = ggml_add_inplace(ctx0,
1712 ggml_mul(ctx0, queries, tfm_layer.norm2_w),
1713 tfm_layer.norm2_b);
1714
1715 // MLP block
1716 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L170
1717 struct ggml_tensor * mlp_out = ggml_mul_mat(ctx0,
1718 tfm_layer.mlp_lin1_w,
1719 queries);
1720
1721 mlp_out = ggml_add_inplace(ctx0, mlp_out, tfm_layer.mlp_lin1_b);
1722
1723 // RELU activation
1724 mlp_out = ggml_relu_inplace(ctx0, mlp_out);
1725 mlp_out = ggml_mul_mat(ctx0, tfm_layer.mlp_lin2_w, mlp_out);
1726
1727 mlp_out = ggml_add_inplace(ctx0, mlp_out, tfm_layer.mlp_lin2_b);
1728
1729 queries = ggml_add_inplace(ctx0, queries, mlp_out);
1730 queries = ggml_norm_inplace(ctx0, queries, hparams.eps_decoder_transformer);
1731 queries = ggml_add_inplace(ctx0,
1732 ggml_mul(ctx0, queries, tfm_layer.norm3_w),
1733 tfm_layer.norm3_b);
1734
1735 // Cross attention block, image embedding attending to tokens
1736 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L175
1737 struct ggml_tensor * q_2 = ggml_add(ctx0, queries, tokens);
1738 struct ggml_tensor * k_2 = ggml_add(ctx0, keys, pos_src);
1739
1740 struct ggml_tensor * cross_attn_img_to_token = sam_decode_mask_transformer_attn(tfm_layer.cross_attn_img_to_token, k_2, q_2, queries, ctx0, model);
1741 keys = ggml_add_inplace(ctx0, keys, cross_attn_img_to_token);
1742 keys = ggml_norm_inplace(ctx0, keys, hparams.eps_decoder_transformer);
1743 keys = ggml_add_inplace(ctx0,
1744 ggml_mul(ctx0, keys, tfm_layer.norm4_w),
1745 tfm_layer.norm4_b);
1746 }
1747
1748 // Apply the final attention layer from the points to the image
1749 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L99
1750 struct ggml_tensor * q = ggml_add(ctx0, queries, tokens);
1751 struct ggml_tensor * k = ggml_add(ctx0, keys, pos_src);
1752
1753 struct ggml_tensor * final_attn_token_to_img = sam_decode_mask_transformer_attn(dec.transformer_final_attn_token_to_img, q, k, keys, ctx0, model);
1754
1755 queries = ggml_add_inplace(ctx0, queries, final_attn_token_to_img);
1756 queries = ggml_norm_inplace(ctx0, queries, hparams.eps_decoder_transformer);
1757 queries = ggml_add_inplace(ctx0,
1758 ggml_mul(ctx0, queries, dec.transformer_norm_final_w),
1759 dec.transformer_norm_final_b);
1760 }
1761
1762
1763 struct ggml_tensor * iou_pred = ggml_view_2d(ctx0, queries, queries->ne[0], queries->ne[2], queries->nb[2], 0);
1764 const int num_mask_tokens = 4; // num_multimask_outputs + 1
1765 struct ggml_tensor * mask_tokens_out = ggml_view_3d(ctx0, queries, queries->ne[0], num_mask_tokens, queries->ne[2], queries->nb[1], num_mask_tokens*queries->nb[1], queries->nb[1]);
1766
1767 // Upscale mask embeddings and predict masks using the mask tokens
1768 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L136
1769 keys = ggml_cont(ctx0, ggml_transpose(ctx0, keys));
1770 keys = ggml_view_4d(ctx0, keys, srcNE[0], srcNE[1], srcNE[2], srcNE[3], srcNE[0]*keys->nb[0], keys->nb[1], keys->nb[2], 0);
1771 // ggml_build_forward_expand(gf, keys);
1772 struct ggml_tensor * upscaled_embedding = {};
1773 {
1774 // ConvTranspose2d
1775 keys = ggml_conv_transpose_2d_p0(ctx0, dec.output_upscaling_0_w, keys, 2);
1776 keys = ggml_add_inplace(ctx0, keys, ggml_repeat(ctx0,
1777 ggml_reshape_3d(ctx0, dec.output_upscaling_0_b, 1, 1, dec.output_upscaling_0_b->ne[0]),
1778 keys));
1779
1780 keys = sam_layer_norm_2d(ctx0, keys, n_img_embd, dec.output_upscaling_1_w, dec.output_upscaling_1_b, hparams.eps);
1781
1782 // GELU activation
1783 keys = ggml_gelu_inplace(ctx0, keys);
1784
1785 // ConvTranspose2d
1786 keys = ggml_conv_transpose_2d_p0(ctx0, dec.output_upscaling_3_w, keys, 2);
1787 keys = ggml_add_inplace(ctx0, ggml_repeat(ctx0,
1788 ggml_reshape_3d(ctx0, dec.output_upscaling_3_b, 1, 1, dec.output_upscaling_3_b->ne[0]),
1789 keys), keys);
1790 // GELU activation
1791 keys = ggml_gelu_inplace(ctx0, keys);
1792 upscaled_embedding = ggml_reshape_3d(ctx0, keys, keys->ne[0]*keys->ne[1], keys->ne[2], keys->ne[3]);
1793 upscaled_embedding = ggml_cont(ctx0, ggml_transpose(ctx0, upscaled_embedding)); // TODO: Shouldn't be needed
1794 }
1795
1796 struct ggml_tensor * hyper_in = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_img_embd/2, num_mask_tokens, mask_tokens_out->ne[2]);
1797
1798 for (int i = 0; i < num_mask_tokens; ++i) {
1799 const auto& mlp = dec.output_hypernet_mlps[i];
1800 struct ggml_tensor * in = ggml_view_2d(ctx0, mask_tokens_out, mask_tokens_out->ne[0], mask_tokens_out->ne[2], mask_tokens_out->nb[1], i*mask_tokens_out->nb[1]);
1801 struct ggml_tensor * out = sam_decode_mask_mlp_relu_3(in, mlp.w_0, mlp.b_0, mlp.w_1, mlp.b_1, mlp.w_2, mlp.b_2, ctx0);
1802 ggml_build_forward_expand(gf, ggml_cpy(ctx0, out, ggml_view_2d(ctx0, hyper_in, hyper_in->ne[0], hyper_in->ne[2], hyper_in->nb[1], i*hyper_in->nb[1])));
1803 }
1804
1805 // swapping the operands yields [W*H, num_mask_tokens, batch] directly (no transpose needed)
1806 struct ggml_tensor * masks = ggml_mul_mat(ctx0, upscaled_embedding, hyper_in);
1807 masks = ggml_reshape_4d(ctx0, masks, keys->ne[0], keys->ne[1], masks->ne[1], keys->ne[3]);
1808
1809 // Generate mask quality predictions
1810 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L146
1811 iou_pred = sam_decode_mask_mlp_relu_3(iou_pred, dec.iou_prediction_head_0_w, dec.iou_prediction_head_0_b, dec.iou_prediction_head_1_w, dec.iou_prediction_head_1_b, dec.iou_prediction_head_2_w, dec.iou_prediction_head_2_b, ctx0);
1812
1813 // Select the correct mask or masks for output
1814 // ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L101
1815 if (multimask_output) {
1816 iou_pred = ggml_cpy(state.ctx, ggml_view_1d(ctx0, iou_pred, iou_pred->ne[0] - 1, iou_pred->nb[0]), state.iou_predictions);
1817 masks = ggml_view_4d(ctx0, masks, masks->ne[0], masks->ne[1], masks->ne[2] - 1, masks->ne[3],
1818 masks->nb[1], masks->nb[2], masks->nb[3], masks->nb[2] /* offset*/);
1819 masks = ggml_cpy(state.ctx, masks, state.low_res_masks);
1820 } else {
1821 iou_pred = ggml_cpy(state.ctx, ggml_view_1d(ctx0, iou_pred, 1, 0), ggml_view_1d(ctx0, state.iou_predictions, 1, 0));
1822 masks = ggml_view_4d(ctx0, masks, masks->ne[0], masks->ne[1], 1, masks->ne[3],
1823 masks->nb[1], masks->nb[2], masks->nb[3], 0);
1824 auto * low_res_mask = ggml_view_4d(ctx0, state.low_res_masks, masks->ne[0], masks->ne[1], 1, masks->ne[3],
1825 masks->nb[1], masks->nb[2], masks->nb[3], 0);
1826 masks = ggml_cpy(state.ctx, masks, low_res_mask);
1827 }
1828
1829 ggml_build_forward_expand(gf, masks);
1830 ggml_build_forward_expand(gf, iou_pred);
1831
1832 ggml_disconnect_node_from_graph(state.low_res_masks);
1833 ggml_disconnect_node_from_graph(state.iou_predictions);
1834
1835 return true;
1836}
1837
1838bool sam_write_masks(const sam_hparams& hparams, int nx, int ny, const sam_state & state, const std::string & fname, const bool multimask_output) {
1839 if (state.low_res_masks->ne[2] == 0) return true;
1840 if (state.low_res_masks->ne[2] != state.iou_predictions->ne[0]) {
1841 printf("Error: number of masks (%d) does not match number of iou predictions (%d)\n", (int)state.low_res_masks->ne[2], (int)state.iou_predictions->ne[0]);
1842 return false;
1843 }
1844
1845 const int n_img_size = hparams.n_img_size();
1846 const float mask_threshold = hparams.mask_threshold;
1847 const float iou_threshold = hparams.iou_threshold;
1848 const float stability_score_threshold = hparams.stability_score_threshold;
1849 const float intersection_threshold = mask_threshold + hparams.stability_score_offset;
1850 const float union_threshold = mask_threshold - hparams.stability_score_offset;
1851
1852 const int ne0 = state.low_res_masks->ne[0];
1853 const int ne1 = state.low_res_masks->ne[1];
1854 const int ne2 = multimask_output ? state.low_res_masks->ne[2] : 1;
1855
1856 // Remove padding and upscale masks to the original image size.
1857 // ref: https://github.com/facebookresearch/segment-anything/blob/efeab7296ab579d4a261e554eca80faf6b33924a/segment_anything/modeling/sam.py#L140
1858
1859 const float preprocess_scale = std::max(nx, ny) / float(n_img_size);
1860 const int cropped_nx = int(nx / preprocess_scale + 0.5f);
1861 const int cropped_ny = int(ny / preprocess_scale + 0.5f);
1862
1863 const float scale_x_1 = (float)ne0 / (float)n_img_size;
1864 const float scale_y_1 = (float)ne1 / (float)n_img_size;
1865
1866 const float scale_x_2 = float(cropped_nx) / float(nx);
1867 const float scale_y_2 = float(cropped_ny) / float(ny);
1868
1869 const auto iou_data = (float*)state.iou_predictions->data;
1870
1871 for (int i = 0; i < ne2; ++i) {
1872 if (iou_threshold > 0.f && iou_data[i] < iou_threshold) {
1873 printf("Skipping mask %d with iou %f below threshold %f\n", i, iou_data[i], iou_threshold);
1874 continue; // Filtering masks with iou below the threshold
1875 }
1876
1877 std::vector<float> mask_data(n_img_size*n_img_size);
1878 {
1879 const float* data = (float *) state.low_res_masks->data + i*ne0*ne1;
1880
1881 for (int iy = 0; iy < n_img_size; ++iy) {
1882 for (int ix = 0; ix < n_img_size; ++ix) {
1883 const float sx = std::max(scale_x_1*(ix + 0.5f) - 0.5f, 0.0f);
1884 const float sy = std::max(scale_y_1*(iy + 0.5f) - 0.5f, 0.0f);
1885
1886 const int x0 = std::max(0, (int)sx);
1887 const int y0 = std::max(0, (int)sy);
1888
1889 const int x1 = std::min(x0 + 1, ne0 - 1);
1890 const int y1 = std::min(y0 + 1, ne1 - 1);
1891
1892 const float dx = sx - x0;
1893 const float dy = sy - y0;
1894
1895 const int j00 = y0*ne0 + x0;
1896 const int j01 = y0*ne0 + x1;
1897 const int j10 = y1*ne0 + x0;
1898 const int j11 = y1*ne0 + x1;
1899
1900 const float v00 = data[j00];
1901 const float v01 = data[j01];
1902 const float v10 = data[j10];
1903 const float v11 = data[j11];
1904
1905 const float v0 = (1-dx)*v00 + dx*v01;
1906 const float v1 = (1-dx)*v10 + dx*v11;
1907
1908 const float v = (1-dy)*v0 + dy*v1;
1909
1910 mask_data[iy*n_img_size + ix] = v;
1911 }
1912 }
1913 }
1914
1915 int intersections = 0;
1916 int unions = 0;
1917 sam_image_u8 res;
1918 int min_iy = ny;
1919 int max_iy = 0;
1920 int min_ix = nx;
1921 int max_ix = 0;
1922 {
1923 const float* data = mask_data.data();
1924
1925 res.nx = nx;
1926 res.ny = ny;
1927 res.data.resize(nx*ny);
1928
1929 for (int iy = 0; iy < ny; ++iy) {
1930 for (int ix = 0; ix < nx; ++ix) {
1931 const float sx = std::max(scale_x_2*(ix + 0.5f) - 0.5f, 0.0f);
1932 const float sy = std::max(scale_y_2*(iy + 0.5f) - 0.5f, 0.0f);
1933
1934 const int x0 = std::max(0, (int)sx);
1935 const int y0 = std::max(0, (int)sy);
1936
1937 const int x1 = std::min(x0 + 1, cropped_nx - 1);
1938 const int y1 = std::min(y0 + 1, cropped_ny - 1);
1939
1940 const float dx = sx - x0;
1941 const float dy = sy - y0;
1942
1943 const int j00 = y0*n_img_size + x0;
1944 const int j01 = y0*n_img_size + x1;
1945 const int j10 = y1*n_img_size + x0;
1946 const int j11 = y1*n_img_size + x1;
1947
1948 const float v00 = data[j00];
1949 const float v01 = data[j01];
1950 const float v10 = data[j10];
1951 const float v11 = data[j11];
1952
1953 const float v0 = (1-dx)*v00 + dx*v01;
1954 const float v1 = (1-dx)*v10 + dx*v11;
1955
1956 const float v = (1-dy)*v0 + dy*v1;
1957
1958 if (v > intersection_threshold) {
1959 intersections++;
1960 }
1961 if (v > union_threshold) {
1962 unions++;
1963 }
1964 if (v > mask_threshold) {
1965 min_iy = std::min(min_iy, iy);
1966 max_iy = std::max(max_iy, iy);
1967 min_ix = std::min(min_ix, ix);
1968 max_ix = std::max(max_ix, ix);
1969
1970 res.data[iy*nx + ix] = 255;
1971 }
1972 }
1973 }
1974 }
1975
1976 const float stability_score = float(intersections) / float(unions);
1977 if (stability_score_threshold > 0.f && stability_score < stability_score_threshold) {
1978 printf("Skipping mask %d with stability score %f below threshold %f\n", i, stability_score, stability_score_threshold);
1979 continue; // Filtering masks with stability score below the threshold
1980 }
1981
1982 printf("Mask %d: iou = %f, stability_score = %f, bbox (%d, %d), (%d, %d)\n",
1983 i, iou_data[i], stability_score, min_ix, max_ix, min_iy, max_iy);
1984
1985 const std::string filename = multimask_output ? fname + std::to_string(i) + ".png" : fname + ".png";
1986 if (!stbi_write_png(filename.c_str(), res.nx, res.ny, 1, res.data.data(), res.nx)) {
1987 printf("%s: failed to write mask %s\n", __func__, filename.c_str());
1988 return false;
1989 }
1990 }
1991
1992
1993 return true;
1994}
1995
1996
1997struct ggml_cgraph * sam_build_fast_graph(
1998 const sam_model & model,
1999 sam_state & state,
2000 const int nx,
2001 const int ny,
2002 const sam_prompt & prompt,
2003 const bool multimask_output) {
2004
2005 struct ggml_init_params ggml_params = {
2006 /*.mem_size =*/ state.buf_compute_fast.size(),
2007 /*.mem_buffer =*/ state.buf_compute_fast.data(),
2008 /*.no_alloc =*/ true, // skip allocating as we use ggml_alloc to allocate exact memory requirements
2009 };
2010
2011 struct ggml_context * ctx0 = ggml_init(ggml_params);
2012 struct ggml_cgraph * gf = ggml_new_graph(ctx0);
2013
2014 prompt_encoder_result enc_res = sam_encode_prompt(model, ctx0, gf, state, prompt);
2015 if (!enc_res.embd_prompt_sparse || !enc_res.embd_prompt_dense) {
2016 fprintf(stderr, "%s: failed to encode prompt\n", __func__);
2017 return {};
2018 }
2019
2020 struct ggml_tensor * pe_img_dense = sam_fill_dense_pe(model, ctx0, gf, state);
2021 if (!pe_img_dense) {
2022 fprintf(stderr, "%s: failed to get dense positional encoding\n", __func__);
2023 return {};
2024 }
2025
2026 if (!sam_decode_mask(model, enc_res, pe_img_dense, ctx0, gf, state, multimask_output)) {
2027 fprintf(stderr, "%s: failed to decode mask\n", __func__);
2028 return {};
2029 }
2030
2031 ggml_free(ctx0);
2032
2033 ggml_gallocr_alloc_graph(state.allocr, gf);
2034
2035 struct ggml_tensor * inp = ggml_graph_get_tensor(gf, "prompt_input");
2036 auto * data = (float *) inp->data;
2037
2038 // Transform prompt (point or box)
2039 {
2040 // https://github.com/facebookresearch/segment-anything/blob/dca509fe793f601edb92606367a655c15ac00fdf/segment_anything/utils/transforms.py#L33
2041 // The point scaling here is greatly simplified but mathematically equivalent.
2042 const auto scale = 1.0F / std::max(nx, ny);
2043
2044 switch (prompt.prompt_type) {
2045 case SAM_PROMPT_TYPE_POINT: {
2046 const auto & pt = prompt.pt;
2047
2048 // set the input by converting the [0, 1] coordinates to [-1, 1]
2049 data[0] = 2.0f*pt.x*scale - 1.0f;
2050 data[1] = 2.0f*pt.y*scale - 1.0f;
2051
2052 // padding
2053 // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L81-L85
2054 data[2] = 2.0f*(0.0f) - 1.0f;
2055 data[3] = 2.0f*(0.0f) - 1.0f;
2056 } break;
2057 case SAM_PROMPT_TYPE_BOX: {
2058 const auto & box = prompt.box;
2059
2060 data[0] = 2.0f*box.x1*scale - 1.0f;
2061 data[1] = 2.0f*box.y1*scale - 1.0f;
2062 data[2] = 2.0f*box.x2*scale - 1.0f;
2063 data[3] = 2.0f*box.y2*scale - 1.0f;
2064 } break;
2065 }
2066 }
2067
2068 // from sam_fill_dense_pe
2069 {
2070 struct ggml_tensor * xy_embed_stacked = ggml_graph_get_tensor(gf, "xy_embed_stacked");
2071 const int32_t n_img_embd = model.hparams.n_img_embd();
2072 const float n_img_embd_inv = 1.0f / n_img_embd;
2073 float * data = (float *) ggml_get_data(xy_embed_stacked);
2074 for (int i = 0; i < n_img_embd; ++i) {
2075 const int row = 2*i*n_img_embd;
2076 const float y_val = 2 * (i + 0.5f) * n_img_embd_inv - 1;
2077 for (int j = 0; j < n_img_embd; ++j) {
2078 const float x_val = 2 * (j + 0.5f) * n_img_embd_inv - 1;
2079 data[row + 2*j + 0] = x_val;
2080 data[row + 2*j + 1] = y_val;
2081 }
2082 }
2083 }
2084
2085 return gf;
2086}
2087
2088void sam_print_usage(int argc, char ** argv, const sam_params & params) {
2089 fprintf(stderr, "usage: %s [options]\n", argv[0]);
2090 fprintf(stderr, "\n");
2091 fprintf(stderr, "options:\n");
2092 fprintf(stderr, " -h, --help show this help message and exit\n");
2093 fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
2094 fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
2095 fprintf(stderr, " -m FNAME, --model FNAME\n");
2096 fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
2097 fprintf(stderr, " -i FNAME, --inp FNAME\n");
2098 fprintf(stderr, " input file (default: %s)\n", params.fname_inp.c_str());
2099 fprintf(stderr, " -o FNAME, --out FNAME\n");
2100 fprintf(stderr, " mask file name prefix (default: %s)\n", params.fname_out.c_str());
2101 fprintf(stderr, " -sm, --single-mask\n");
2102 fprintf(stderr, " single mask output (default multi mask output)\n");
2103 fprintf(stderr, "SAM hyperparameters:\n");
2104 fprintf(stderr, " -mt FLOAT, --mask-threshold\n");
2105 fprintf(stderr, " mask threshold (default: %f)\n", params.mask_threshold);
2106 fprintf(stderr, " -it FLOAT, --iou-threshold\n");
2107 fprintf(stderr, " iou threshold (default: %f)\n", params.iou_threshold);
2108 fprintf(stderr, " -st FLOAT, --score-threshold\n");
2109 fprintf(stderr, " score threshold (default: %f)\n", params.stability_score_threshold);
2110 fprintf(stderr, " -so FLOAT, --score-offset\n");
2111 fprintf(stderr, " score offset (default: %f)\n", params.stability_score_offset);
2112 fprintf(stderr, " -e FLOAT, --epsilon\n");
2113 fprintf(stderr, " epsilon (default: %f)\n", params.eps);
2114 fprintf(stderr, " -ed FLOAT, --epsilon-decoder-transformer\n");
2115 fprintf(stderr, " epsilon decoder transformer (default: %f)\n", params.eps_decoder_transformer);
2116 fprintf(stderr, "SAM prompt:\n");
2117 fprintf(stderr, " -p [x,y], --point-prompt\n");
2118 fprintf(stderr, " point to be used as prompt for SAM (default: %f,%f). Must be in a format FLOAT,FLOAT \n", params.prompt.pt.x, params.prompt.pt.y);
2119 fprintf(stderr, " -b [x1,y1,x2,y2], --box-prompt\n");
2120 fprintf(stderr, " box to be used as prompt for SAM (default: %f,%f,%f,%f). Must be in a format FLOAT,FLOAT,FLOAT,FLOAT \n",
2121 params.prompt.box.x1, params.prompt.box.y1, params.prompt.box.x2, params.prompt.box.y2);
2122 fprintf(stderr, "\n");
2123}
2124
2125bool sam_params_parse(int argc, char ** argv, sam_params & params) {
2126
2127 bool use_point_prompt = false;
2128 bool use_box_prompt = false;
2129
2130 for (int i = 1; i < argc; i++) {
2131 std::string arg = argv[i];
2132
2133 if (arg == "-s" || arg == "--seed") {
2134 params.seed = std::stoi(argv[++i]);
2135 } else if (arg == "-t" || arg == "--threads") {
2136 params.n_threads = std::stoi(argv[++i]);
2137 } else if (arg == "-m" || arg == "--model") {
2138 params.model = argv[++i];
2139 } else if (arg == "-i" || arg == "--inp") {
2140 params.fname_inp = argv[++i];
2141 } else if (arg == "-o" || arg == "--out") {
2142 params.fname_out = argv[++i];
2143 } else if (arg == "-sm" || arg == "--single-mask") {
2144 params.multimask_output = false;
2145 } else if (arg == "-mt" || arg == "--mask-threshold") {
2146 params.mask_threshold = std::stof(argv[++i]);
2147 } else if (arg == "-it" || arg == "--iou-threshold") {
2148 params.iou_threshold = std::stof(argv[++i]);
2149 } else if (arg == "-st" || arg == "--score-threshold") {
2150 params.stability_score_threshold = std::stof(argv[++i]);
2151 } else if (arg == "-so" || arg == "--score-offset") {
2152 params.stability_score_offset = std::stof(argv[++i]);
2153 } else if (arg == "-e" || arg == "--epsilon") {
2154 params.eps = std::stof(argv[++i]);
2155 } else if (arg == "-ed" || arg == "--epsilon-decoder-transformer") {
2156 params.eps_decoder_transformer = std::stof(argv[++i]);
2157 } else if (arg == "-p" || arg == "--point-prompt") {
2158 // TODO multiple points per model invocation
2159 use_point_prompt = true;
2160 char* point = argv[++i];
2161
2162 char* coord = strtok(point, ",");
2163 if (!coord){
2164 fprintf(stderr, "Error while parsing prompt!\n");
2165 exit(1);
2166 }
2167 params.prompt.pt.x = std::stof(coord);
2168
2169 coord = strtok(NULL, ",");
2170 if (!coord){
2171 fprintf(stderr, "Error while parsing prompt!\n");
2172 exit(1);
2173 }
2174 params.prompt.pt.y = std::stof(coord);
2175 } else if (arg == "-b" || arg == "--box-prompt") {
2176 use_box_prompt = true;
2177 char * box_prompt = argv[++i];
2178 float box_vals[4];
2179
2180 char * val = strtok(box_prompt, ",");
2181 if (!val) {
2182 fprintf(stderr, "Error while parsing prompt!\n");
2183 exit(1);
2184 }
2185 box_vals[0] = std::stof(val);
2186
2187 for (int j = 1; j < 4; ++j) {
2188 char * val = strtok(NULL, ",");
2189 if (!val) {
2190 fprintf(stderr, "Error while parsing prompt!\n");
2191 exit(1);
2192 }
2193 box_vals[j] = std::stof(val);
2194 }
2195
2196 params.prompt.box.x1 = box_vals[0];
2197 params.prompt.box.y1 = box_vals[1];
2198 params.prompt.box.x2 = box_vals[2];
2199 params.prompt.box.y2 = box_vals[3];
2200 } else if (arg == "-h" || arg == "--help") {
2201 sam_print_usage(argc, argv, params);
2202 exit(0);
2203 } else {
2204 fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
2205 sam_print_usage(argc, argv, params);
2206 exit(0);
2207 }
2208 }
2209
2210 if (use_box_prompt && use_point_prompt) {
2211 fprintf(stderr, "Error: use either point or box prompt, not both.\n");
2212 exit(1);
2213 }
2214
2215 params.prompt.prompt_type = SAM_PROMPT_TYPE_POINT;
2216 if (use_box_prompt) {
2217 params.prompt.prompt_type = SAM_PROMPT_TYPE_BOX;
2218 }
2219
2220 return true;
2221}
2222
2223
2224int main(int argc, char ** argv) {
2225 ggml_time_init();
2226 const int64_t t_main_start_us = ggml_time_us();
2227
2228 sam_params params;
2229 params.model = "models/sam-vit-b/ggml-model-f16.bin";
2230
2231 sam_model model;
2232 sam_state state;
2233 int64_t t_load_us = 0;
2234
2235 if (sam_params_parse(argc, argv, params) == false) {
2236 return 1;
2237 }
2238
2239 if (params.seed < 0) {
2240 params.seed = time(NULL);
2241 }
2242 fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
2243
2244 // load the image
2245 sam_image_u8 img0;
2246 if (!sam_image_load_from_file(params.fname_inp, img0)) {
2247 fprintf(stderr, "%s: failed to load image from '%s'\n", __func__, params.fname_inp.c_str());
2248 return 1;
2249 }
2250 fprintf(stderr, "%s: loaded image '%s' (%d x %d)\n", __func__, params.fname_inp.c_str(), img0.nx, img0.ny);
2251
2252 // preprocess to f32
2253 sam_image_f32 img1;
2254 if (!sam_image_preprocess(img0, img1)) {
2255 fprintf(stderr, "%s: failed to preprocess image\n", __func__);
2256 return 1;
2257 }
2258 fprintf(stderr, "%s: preprocessed image (%d x %d)\n", __func__, img1.nx, img1.ny);
2259
2260
2261 // load the model
2262 {
2263 const int64_t t_start_us = ggml_time_us();
2264
2265 if (!sam_model_load(params, model)) {
2266 fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
2267 return 1;
2268 }
2269
2270 t_load_us = ggml_time_us() - t_start_us;
2271 }
2272
2273 {
2274 static size_t buf_size = 256u*1024*1024;
2275
2276 struct ggml_init_params ggml_params = {
2277 /*.mem_size =*/ buf_size,
2278 /*.mem_buffer =*/ NULL,
2279 /*.no_alloc =*/ false,
2280 };
2281
2282 state.ctx = ggml_init(ggml_params);
2283
2284 state.embd_img = ggml_new_tensor_3d(state.ctx, GGML_TYPE_F32,
2285 model.hparams.n_img_embd(), model.hparams.n_img_embd(), model.hparams.n_enc_out_chans);
2286
2287 state.low_res_masks = ggml_new_tensor_3d(state.ctx, GGML_TYPE_F32,
2288 model.hparams.n_enc_out_chans, model.hparams.n_enc_out_chans, 3);
2289
2290 state.iou_predictions = ggml_new_tensor_1d(state.ctx, GGML_TYPE_F32, 3);
2291 }
2292
2293 // Encode image
2294 {
2295 state.buf_compute_img_enc.resize(ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead());
2296 state.allocr = ggml_gallocr_new(ggml_backend_cpu_buffer_type());
2297
2298 struct ggml_cgraph * gf = sam_encode_image(model, state, img1);
2299 if (!gf) {
2300 fprintf(stderr, "%s: failed to encode image\n", __func__);
2301 return 1;
2302 }
2303
2304 ggml_graph_compute_helper(state.work_buffer, gf, params.n_threads);
2305
2306 // print_t_f32("embd_img", state.embd_img);
2307
2308 ggml_gallocr_free(state.allocr);
2309 state.allocr = NULL;
2310 state.work_buffer.clear();
2311 }
2312
2313 // Encode prompt and decode mask
2314 {
2315 state.buf_compute_fast.resize(ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead());
2316 state.allocr = ggml_gallocr_new(ggml_backend_cpu_buffer_type());
2317
2318 switch (params.prompt.prompt_type) {
2319 case SAM_PROMPT_TYPE_POINT:
2320 fprintf(stderr, "Using point prompt: (%f, %f)\n", params.prompt.pt.x, params.prompt.pt.y);
2321 break;
2322 case SAM_PROMPT_TYPE_BOX:
2323 fprintf(stderr, "Using box prompt: (%f, %f, %f, %f)\n",
2324 params.prompt.box.x1,
2325 params.prompt.box.y1,
2326 params.prompt.box.x2,
2327 params.prompt.box.y2);
2328 break;
2329 }
2330
2331 struct ggml_cgraph * gf = sam_build_fast_graph(model, state, img0.nx, img0.ny, params.prompt, params.multimask_output);
2332 if (!gf) {
2333 fprintf(stderr, "%s: failed to build fast graph\n", __func__);
2334 return 1;
2335 }
2336
2337 ggml_graph_compute_helper(state.work_buffer, gf, params.n_threads);
2338
2339 //print_t_f32("iou_predictions", state.iou_predictions);
2340 //print_t_f32("low_res_masks", state.low_res_masks);
2341 ggml_gallocr_free(state.allocr);
2342 state.allocr = NULL;
2343 }
2344
2345 if (!sam_write_masks(model.hparams, img0.nx, img0.ny, state, params.fname_out, params.multimask_output)) {
2346 fprintf(stderr, "%s: failed to write masks\n", __func__);
2347 return 1;
2348 }
2349
2350 // report timing
2351 {
2352 const int64_t t_main_end_us = ggml_time_us();
2353
2354 fprintf(stderr, "\n\n");
2355 fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
2356 fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
2357 }
2358
2359 ggml_free(model.ctx);
2360
2361 return 0;
2362}