-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
1635 lines (1321 loc) · 66.5 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using GGMLSharp;
using ModelLoader;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using static GGMLSharp.Structs;
namespace SAM
{
internal class Program
{
private static Custom1OpDelegate opSin = new Custom1OpDelegate(SamSin);
private static Custom1OpDelegate opCos = new Custom1OpDelegate(SamCos);
static void Main(string[] args)
{
// First you shold download the sam_vit_b ModelPath and move it to Assets folder.
// The download link is: https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
SamParams samParam = new SamParams()
{
IouThreshold = 0.9f,
StabilityScoreThreshold = 0.9f,
Point = new PointF(274.0f, 244.0f),
ModelPath = @"./Assets/sam_vit_b_01ec64.pth",
ImageInputPath = @"./Assets/example.jpg",
Threads = 16,
};
// Load ModelPath
SamModel model = LoadModel(samParam);
Console.WriteLine("Model Loaded.");
Console.WriteLine("Load image from file...");
// Load Img
SamImageU8 imgU8 = LoadImageFromFile(samParam.ImageInputPath);
SamImageF32 imgF32 = PreprocessImage(imgU8);
Console.WriteLine("Init state");
// Init state
SamState state = new SamState();
{
ulong bufSize = 256u * 1024 * 1024;
state.context = new SafeGGmlContext(IntPtr.Zero, bufSize);
state.embdImg = state.context.NewTensor3d(Structs.GGmlType.GGML_TYPE_F32, model.hparams.ImgEmbdCount, model.hparams.ImgEmbdCount, model.hparams.EncoderOutChans);
state.lowResMasks = state.context.NewTensor3d(Structs.GGmlType.GGML_TYPE_F32, model.hparams.EncoderOutChans, model.hparams.EncoderOutChans, 3);
state.iouPredictions = state.context.NewTensor1d(Structs.GGmlType.GGML_TYPE_F32, 3);
}
// Encode image
{
Console.WriteLine("Encoding the image...");
state.allocr = new SafeGGmlGraphAllocr();
SafeGGmlGraph gf = SamEncodeImage(model, state, imgF32);
if (gf.IsInvalid)
{
throw new Exception("failed to encode image");
}
GraphComputeHelper(gf, samParam.Threads);
state.allocr.Free();
Console.WriteLine("Image encoded done.");
}
// Compute the masks
{
state.allocr = new SafeGGmlGraphAllocr();
// TODO: more varied prompts
Console.WriteLine($"prompt Point: ({samParam.Point.X}, {samParam.Point.Y})");
Console.WriteLine("Computing the mask...");
SafeGGmlGraph graph = SamBuildFastGraph(model, state, imgU8.Width, imgU8.Height, samParam.Point);
if (graph.IsInvalid)
{
throw new Exception("failed to build fast graph");
}
GraphComputeHelper(graph, samParam.Threads);
state.allocr.Free();
Console.WriteLine("Masks have got.");
}
// Write masks.
Console.WriteLine("Writing masks...");
WriteMasks(model.hparams, imgU8.Width, imgU8.Height, state, samParam.OutputNameHeader);
Console.WriteLine("Write masks done.");
Console.ReadKey();
}
class SamHparams
{
public int EncoderState = 768;
public int EncoderLayer = 12;
public int EncoderHead = 12;
public int EncoderOutChans = 256;
public int PtEmbd = 4;
public int DecoderHeadsCount = 8;
public int Type = 1;
public float MaskThreshold = 0.0f;
public float IouThreshold = 0.88f;
public float StabilityScoreThreshold = 0.95f;
public float StabilityScoreOffset = 1.0f;
public float Eps = 1e-6f;
public float EpsDecoderTransformer = 1e-5f;
public int EncHeadDim => EncoderState / EncoderHead;
public int ImgSize => 1024;
public int WindowSize => 14;
public int PatchSize => 16;
public int ImgEmbdCount => ImgSize / PatchSize;
public int[] GlobalAttnIndices
{
get
{
switch (EncoderState)
{
case 768: return new int[] { 2, 5, 8, 11 };
case 1024: return new int[] { 5, 11, 17, 23 };
case 1280: return new int[] { 7, 15, 23, 31 };
default:
{
throw new ArgumentOutOfRangeException($"unsupported EncoderState = {EncoderState}");
}
};
}
}
public bool IsGlobalAttn(int layer)
{
return GlobalAttnIndices.Contains(layer);
}
};
// RGB uint8 image
struct SamImageU8
{
public int Width;
public int Height;
public byte[] Data;
};
// RGB float32 image
// Memory layout: RGBRGBRGB...
struct SamImageF32
{
public int Width;
public int Height;
public float[] Data;
};
class SamModel
{
public SamHparams hparams = new SamHparams();
public SamEncoderImage encoderImg;
public SamEncoderPrompt encoderPrompt;
public SamDecoderMask decoderMask;
public SafeGGmlContext context;
};
struct SamLayerEnc
{
public SafeGGmlTensor norm1_w;
public SafeGGmlTensor norm1_b;
public SafeGGmlTensor rel_pos_w;
public SafeGGmlTensor rel_pos_h;
public SafeGGmlTensor qkv_w;
public SafeGGmlTensor qkv_b;
public SafeGGmlTensor proj_w;
public SafeGGmlTensor proj_b;
public SafeGGmlTensor norm2_w;
public SafeGGmlTensor norm2_b;
public SafeGGmlTensor mlp_lin1_w;
public SafeGGmlTensor mlp_lin1_b;
public SafeGGmlTensor mlp_lin2_w;
public SafeGGmlTensor mlp_lin2_b;
};
struct SamEncoderImage
{
public SafeGGmlTensor pe;
public SafeGGmlTensor proj_w;
public SafeGGmlTensor proj_b;
public SafeGGmlTensor neck_conv_0;
public SafeGGmlTensor neck_norm_0_w;
public SafeGGmlTensor neck_norm_0_b;
public SafeGGmlTensor neck_conv_1;
public SafeGGmlTensor neck_norm_1_w;
public SafeGGmlTensor neck_norm_1_b;
public SamLayerEnc[] layers;
};
struct SamEncoderPrompt
{
public SafeGGmlTensor pe;
public SafeGGmlTensor not_a_pt_embd_w;
public SafeGGmlTensor[] pt_embd;
public SafeGGmlTensor no_mask_embd_w;
};
struct SamLayerDecTransformerAttn
{
// q_proj
public SafeGGmlTensor q_w;
public SafeGGmlTensor q_b;
// k_proj
public SafeGGmlTensor k_w;
public SafeGGmlTensor k_b;
// v_proj
public SafeGGmlTensor v_w;
public SafeGGmlTensor v_b;
// out_proj
public SafeGGmlTensor out_w;
public SafeGGmlTensor out_b;
};
struct SamLayerDecTransformer
{
public SamLayerDecTransformerAttn self_attn;
// norm1
public SafeGGmlTensor norm1_w;
public SafeGGmlTensor norm1_b;
public SamLayerDecTransformerAttn cross_attn_token_to_img;
// norm2
public SafeGGmlTensor norm2_w;
public SafeGGmlTensor norm2_b;
// mlp.lin1
public SafeGGmlTensor mlp_lin1_w;
public SafeGGmlTensor mlp_lin1_b;
// mlp.lin2
public SafeGGmlTensor mlp_lin2_w;
public SafeGGmlTensor mlp_lin2_b;
// norm3
public SafeGGmlTensor norm3_w;
public SafeGGmlTensor norm3_b;
// norm4
public SafeGGmlTensor norm4_w;
public SafeGGmlTensor norm4_b;
public SamLayerDecTransformerAttn cross_attn_img_to_token;
};
struct SamLayerDecOutputHypernetMlps
{
// mlps_*.layers.0
public SafeGGmlTensor w_0;
public SafeGGmlTensor b_0;
// mlps_*.layers.1
public SafeGGmlTensor w_1;
public SafeGGmlTensor b_1;
// mlps_*.layers.2
public SafeGGmlTensor w_2;
public SafeGGmlTensor b_2;
};
struct SamDecoderMask
{
public SamLayerDecTransformer[] transformer_layers;
// trasnformer.final_attn_token_to_image
public SamLayerDecTransformerAttn transformer_final_attn_token_to_img;
// transformer.norm_final
public SafeGGmlTensor transformer_norm_final_w;
public SafeGGmlTensor transformer_norm_final_b;
// output_upscaling.0
public SafeGGmlTensor output_upscaling_0_w;
public SafeGGmlTensor output_upscaling_0_b;
// output_upscaling.1
public SafeGGmlTensor output_upscaling_1_w;
public SafeGGmlTensor output_upscaling_1_b;
// output_upscaling.3
public SafeGGmlTensor output_upscaling_3_w;
public SafeGGmlTensor output_upscaling_3_b;
// output_hypernetworks_mlps
public SamLayerDecOutputHypernetMlps[] output_hypernet_mlps;
// iou_prediction_head.0
public SafeGGmlTensor iou_prediction_head_0_w;
public SafeGGmlTensor iou_prediction_head_0_b;
// iou_prediction_head.1
public SafeGGmlTensor iou_prediction_head_1_w;
public SafeGGmlTensor iou_prediction_head_1_b;
// iou_prediction_head.2
public SafeGGmlTensor iou_prediction_head_2_w;
public SafeGGmlTensor iou_prediction_head_2_b;
// iou_token.weight
public SafeGGmlTensor iou_token_w;
// mask_tokens.weight
public SafeGGmlTensor mask_tokens_w;
};
struct SamState
{
public SafeGGmlTensor embdImg;
public SafeGGmlTensor lowResMasks;
public SafeGGmlTensor iouPredictions;
// ggml_tensor * tmp_save = {};
public SafeGGmlContext context;
public SafeGGmlGraphAllocr allocr;
};
class SamParams
{
public int Seed = -1; // RNG Seed
public int Threads = 4;
public string ModelPath = "./Assets/sam_vit_b_01ec64.pth"; // ModelPath path
public string ImageInputPath = "./Assets/example.jpg";
public string OutputNameHeader = "img.out";
public float MaskThreshold = 0.0f;
public float IouThreshold = 0.88f;
public float StabilityScoreThreshold = 0.95f;
public float StabilityScoreOffset = 1.0f;
public float Eps = 1e-6f;
public float EpsDecoderTransformer = 1e-5f;
public PointF Point = new PointF(414.375f, 162.796875f);
};
static void DisconnectNodeFromGraph(SafeGGmlTensor t)
{
t.Operations = Structs.GGmlOperation.GGML_OP_NONE;
for (int i = 0; i < Structs.GGML_MAX_SRC; i++)
{
t.Sources[i].Dispose();
}
}
static void GraphComputeHelper(SafeGGmlGraph graph, int threads)
{
ulong mem_size = Common.TensorOverheadLength * Structs.GGML_DEFAULT_GRAPH_SIZE * (ulong)graph.NodeCount + Common.GraphOverheadLength;
SafeGGmlContext context = new SafeGGmlContext(IntPtr.Zero, mem_size, false);
graph.ComputeWithGGmlContext(context, threads);
}
static void SamSin(SafeGGmlTensor dst, SafeGGmlTensor src, int ith, int nth, IntPtr userdata)
{
if (userdata != IntPtr.Zero)
{
throw new Exception("userdata is not null");
}
if (!dst.AreSameShape(src))
{
throw new Exception("dst and src are not the same shape");
}
if (!dst.IsContiguous())
{
throw new Exception("des is not contiguous");
}
if (!src.IsContiguous())
{
throw new Exception("src is not contiguous");
}
float[] src_data = GGMLSharp.DataConverter.ConvertToFloats(src.GetData());
int ne = (int)dst.ElementsCount;
int dr = (ne + nth - 1) / nth;
int ie0 = dr * ith;
int ie1 = Math.Min(ie0 + dr, ne);
for (int i = ie0; i < ie1; ++i)
{
dst.SetData((float)Math.Sin(src_data[i]), i);
}
}
static void SamCos(SafeGGmlTensor dst, SafeGGmlTensor src, int ith, int nth, IntPtr userdata)
{
if (userdata != IntPtr.Zero)
{
throw new Exception("userdata is not null");
}
if (!dst.AreSameShape(src))
{
throw new Exception("dst and src are not the same shape");
}
if (!dst.IsContiguous())
{
throw new Exception("des is not contiguous");
}
if (!src.IsContiguous())
{
throw new Exception("src is not contiguous");
}
float[] src_data = GGMLSharp.DataConverter.ConvertToFloats(src.GetData());
int ne = (int)dst.ElementsCount;
int dr = (ne + nth - 1) / nth;
int ie0 = dr * ith;
int ie1 = Math.Min(ie0 + dr, ne);
for (int i = ie0; i < ie1; ++i)
{
dst.SetData((float)Math.Cos(src_data[i]), i);
}
}
static SamImageU8 LoadImageFromFile(string fname)
{
Bitmap bitmap = new Bitmap(fname);
SamImageU8 img = new SamImageU8();
img.Width = bitmap.Width;
img.Height = bitmap.Height;
img.Data = new byte[img.Width * img.Height * 3];
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(bitmapData.Scan0, img.Data, 0, img.Data.Length);
bitmap.UnlockBits(bitmapData);
return img;
}
// ref: https://github.com/facebookresearch/segment-anything/blob/efeab7296ab579d4a261e554eca80faf6b33924a/segment_anything/modeling/sam.py#L164
// resize largest dimension to 1024
// normalize: x = (x - mean) / std
// mean = [123.675, 116.28, 103.53]
// std = [58.395, 57.12, 57.375]
// TODO: why are these hardcoded !?
// pad to 1024x1024
// TODO: for some reason, this is not numerically identical to pytorch's interpolation
static SamImageF32 PreprocessImage(SamImageU8 img)
{
SamImageF32 res = new SamImageF32();
int nx = img.Width;
int ny = img.Height;
int nx2 = 1024;
int ny2 = 1024;
res.Width = nx2;
res.Height = ny2;
res.Data = new float[3 * nx2 * ny2];
float scale = (float)Math.Max(nx, ny) / 1024.0f;
Console.WriteLine($"scale = {scale}");
int nx3 = (int)(nx / scale + 0.5f);
int ny3 = (int)(ny / scale + 0.5f);
float[] m3 = { 123.675f, 116.280f, 103.530f };
float[] s3 = { 58.395f, 57.120f, 57.375f };
for (int y = 0; y < ny3; y++)
{
for (int x = 0; x < nx3; x++)
{
for (int c = 0; c < 3; c++)
{
// linear interpolation
float sx = (x + 0.5f) * scale - 0.5f;
float sy = (y + 0.5f) * scale - 0.5f;
int x0 = Math.Max(0, (int)Math.Floor(sx));
int y0 = Math.Max(0, (int)Math.Floor(sy));
int x1 = Math.Min(x0 + 1, nx - 1);
int y1 = Math.Min(y0 + 1, ny - 1);
float dx = sx - x0;
float dy = sy - y0;
int j00 = 3 * (y0 * nx + x0) + c;
int j01 = 3 * (y0 * nx + x1) + c;
int j10 = 3 * (y1 * nx + x0) + c;
int j11 = 3 * (y1 * nx + x1) + c;
float v00 = img.Data[j00];
float v01 = img.Data[j01];
float v10 = img.Data[j10];
float v11 = img.Data[j11];
float v0 = v00 * (1.0f - dx) + v01 * dx;
float v1 = v10 * (1.0f - dx) + v11 * dx;
float v = v0 * (1.0f - dy) + v1 * dy;
double v2 = Math.Min(Math.Max(Math.Round(v), 0.0f), 255.0f);
int i = 3 * (y * nx3 + x) + c;
res.Data[i] = ((float)(v2) - m3[c]) / s3[c];
}
}
}
return res;
}
static SamModel LoadModel(SamParams samParams)
{
if (!File.Exists(samParams.ModelPath))
{
throw new FileNotFoundException("Model file not found");
}
PickleLoader modelLoader = new PickleLoader();
Console.WriteLine($"loading ModelPath from {samParams.ModelPath} - please wait ...");
List<Tensor> tensors = modelLoader.ReadTensorsInfoFromFile(samParams.ModelPath);
Console.WriteLine($"ModelPath header loaded, total layers is: {tensors.Count}");
ulong contextSize = 0;
tensors.ForEach(a =>
{
ulong tensorSize = Common.GetGGmlTypeSize(a.Type);
a.Shape.ForEach(ne =>
{
tensorSize *= (ulong)ne;
});
contextSize += tensorSize;
});
contextSize += Common.TensorOverheadLength * (ulong)tensors.Count;
Console.WriteLine("Total context size: " + (float)contextSize / 1024 / 1024 + " MB");
SafeGGmlContext context = new SafeGGmlContext(IntPtr.Zero, contextSize, false);
SamModel model = new SamModel();
model.context = context;
//SamHparams hparams = ModelPath.hparams;
SamHparams hparams = new SamHparams
{
Eps = samParams.Eps,
EpsDecoderTransformer = samParams.EpsDecoderTransformer,
IouThreshold = samParams.IouThreshold,
MaskThreshold = samParams.MaskThreshold,
StabilityScoreOffset = samParams.StabilityScoreOffset,
StabilityScoreThreshold = samParams.StabilityScoreThreshold,
};
model.hparams = hparams;
int encState = hparams.EncoderState;
int encLayer = hparams.EncoderLayer;
int encHeadDim = hparams.EncHeadDim;
int encoderOutChans = hparams.EncoderOutChans;
int ptEmbd = hparams.PtEmbd;
int imgEmbdCount = hparams.ImgEmbdCount;
int windowSize = hparams.WindowSize;
int patchSize = hparams.PatchSize;
// image encoder
{
model.encoderImg.pe = GetTensorFromName(context, modelLoader, tensors, "image_encoder.pos_embed", new long[] { encState, imgEmbdCount, imgEmbdCount });
model.encoderImg.proj_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.patch_embed.proj.weight", new long[] { patchSize, patchSize, 3, encState }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.proj_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.patch_embed.proj.bias", new long[] { 1, 1, encState });
model.encoderImg.neck_conv_0 = GetTensorFromName(context, modelLoader, tensors, "image_encoder.neck.0.weight", new long[] { 1, 1, encState, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.neck_conv_1 = GetTensorFromName(context, modelLoader, tensors, "image_encoder.neck.2.weight", new long[] { 3, 3, encoderOutChans, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.neck_norm_0_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.neck.1.weight");
model.encoderImg.neck_norm_0_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.neck.1.bias");
model.encoderImg.neck_norm_1_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.neck.3.weight");
model.encoderImg.neck_norm_1_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.neck.3.bias");
model.encoderImg.layers = new SamLayerEnc[model.hparams.EncoderLayer];
for (int i = 0; i < model.hparams.EncoderLayer; ++i)
{
model.encoderImg.layers[i].norm1_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".norm1.weight");
model.encoderImg.layers[i].norm1_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".norm1.bias");
if (hparams.IsGlobalAttn(i))
{
model.encoderImg.layers[i].rel_pos_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.rel_pos_w", new long[] { encHeadDim, 2 * imgEmbdCount - 1 }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.layers[i].rel_pos_h = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.rel_pos_h", new long[] { encHeadDim, 2 * imgEmbdCount - 1 }, Structs.GGmlType.GGML_TYPE_F16);
}
else
{
model.encoderImg.layers[i].rel_pos_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.rel_pos_w", new long[] { encHeadDim, 2 * windowSize - 1 }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.layers[i].rel_pos_h = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.rel_pos_h", new long[] { encHeadDim, 2 * windowSize - 1 }, Structs.GGmlType.GGML_TYPE_F16);
}
model.encoderImg.layers[i].qkv_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.qkv.weight", new long[] { encState, 3 * encState, 1, 1 }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.layers[i].qkv_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.qkv.bias");
model.encoderImg.layers[i].proj_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.proj.weight");
model.encoderImg.layers[i].proj_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".attn.proj.bias");
model.encoderImg.layers[i].norm2_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".norm2.weight");
model.encoderImg.layers[i].norm2_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".norm2.bias");
model.encoderImg.layers[i].mlp_lin1_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".mlp.lin1.weight", new long[] { encState, 4 * encState }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.layers[i].mlp_lin1_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".mlp.lin1.bias");
model.encoderImg.layers[i].mlp_lin2_w = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".mlp.lin2.weight", new long[] { 4 * encState, encState }, Structs.GGmlType.GGML_TYPE_F16);
model.encoderImg.layers[i].mlp_lin2_b = GetTensorFromName(context, modelLoader, tensors, "image_encoder.blocks." + i + ".mlp.lin2.bias");
}
}
// prompt encoder
{
model.encoderPrompt.pe = GetTensorFromName(context, modelLoader, tensors, "prompt_encoder.pe_layer.positional_encoding_gaussian_matrix", new long[] { encoderOutChans / 2, 2 }, Structs.GGmlType.GGML_TYPE_F32);
model.encoderPrompt.not_a_pt_embd_w = GetTensorFromName(context, modelLoader, tensors, "prompt_encoder.not_a_point_embed.weight", new long[] { encoderOutChans, 1 });
model.encoderPrompt.no_mask_embd_w = GetTensorFromName(context, modelLoader, tensors, "prompt_encoder.no_mask_embed.weight", new long[] { encoderOutChans, 1 });
model.encoderPrompt.pt_embd = new SafeGGmlTensor[model.hparams.PtEmbd];
for (int i = 0; i < model.hparams.PtEmbd; i++)
{
model.encoderPrompt.pt_embd[i] = GetTensorFromName(context, modelLoader, tensors, "prompt_encoder.point_embeddings." + i + ".weight", new long[] { encoderOutChans, 1 });
}
}
// mask decoder
{
int tfm_layers_count = 2;
model.decoderMask.transformer_layers = new SamLayerDecTransformer[tfm_layers_count];
for (int i = 0; i < tfm_layers_count; ++i)
{
string prefix = "mask_decoder.transformer.layers." + i + ".";
model.decoderMask.transformer_layers[i].self_attn.q_w = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.q_proj.weight");
model.decoderMask.transformer_layers[i].self_attn.q_b = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.q_proj.bias");
model.decoderMask.transformer_layers[i].self_attn.k_w = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.k_proj.weight");
model.decoderMask.transformer_layers[i].self_attn.k_b = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.k_proj.bias");
model.decoderMask.transformer_layers[i].self_attn.v_w = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.v_proj.weight");
model.decoderMask.transformer_layers[i].self_attn.v_b = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.v_proj.bias");
model.decoderMask.transformer_layers[i].self_attn.out_w = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.out_proj.weight");
model.decoderMask.transformer_layers[i].self_attn.out_b = GetTensorFromName(context, modelLoader, tensors, prefix + "self_attn.out_proj.bias");
model.decoderMask.transformer_layers[i].norm1_w = GetTensorFromName(context, modelLoader, tensors, prefix + "norm1.weight");
model.decoderMask.transformer_layers[i].norm1_b = GetTensorFromName(context, modelLoader, tensors, prefix + "norm1.bias");
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.q_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.q_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.q_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.q_proj.bias");
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.k_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.k_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.k_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.k_proj.bias");
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.v_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.v_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.v_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.v_proj.bias");
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.out_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.out_proj.weight", new long[] { encoderOutChans / 2, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_token_to_img.out_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_token_to_image.out_proj.bias");
model.decoderMask.transformer_layers[i].norm2_w = GetTensorFromName(context, modelLoader, tensors, prefix + "norm2.weight");
model.decoderMask.transformer_layers[i].norm2_b = GetTensorFromName(context, modelLoader, tensors, prefix + "norm2.bias");
model.decoderMask.transformer_layers[i].mlp_lin1_w = GetTensorFromName(context, modelLoader, tensors, prefix + "mlp.lin1.weight", new long[] { encoderOutChans, 8 * encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].mlp_lin1_b = GetTensorFromName(context, modelLoader, tensors, prefix + "mlp.lin1.bias");
model.decoderMask.transformer_layers[i].mlp_lin2_w = GetTensorFromName(context, modelLoader, tensors, prefix + "mlp.lin2.weight", new long[] { 8 * encoderOutChans, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].mlp_lin2_b = GetTensorFromName(context, modelLoader, tensors, prefix + "mlp.lin2.bias");
model.decoderMask.transformer_layers[i].norm3_w = GetTensorFromName(context, modelLoader, tensors, prefix + "norm3.weight");
model.decoderMask.transformer_layers[i].norm3_b = GetTensorFromName(context, modelLoader, tensors, prefix + "norm3.bias");
model.decoderMask.transformer_layers[i].norm4_w = GetTensorFromName(context, modelLoader, tensors, prefix + "norm4.weight");
model.decoderMask.transformer_layers[i].norm4_b = GetTensorFromName(context, modelLoader, tensors, prefix + "norm4.bias");
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.q_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.q_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.q_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.q_proj.bias");
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.k_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.k_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.k_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.k_proj.bias");
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.v_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.v_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.v_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.v_proj.bias");
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.out_w = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.out_proj.weight", new long[] { encoderOutChans / 2, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_layers[i].cross_attn_img_to_token.out_b = GetTensorFromName(context, modelLoader, tensors, prefix + "cross_attn_image_to_token.out_proj.bias");
}
model.decoderMask.transformer_final_attn_token_to_img.q_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.q_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_final_attn_token_to_img.q_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.q_proj.bias");
model.decoderMask.transformer_final_attn_token_to_img.k_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.k_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_final_attn_token_to_img.k_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.k_proj.bias");
model.decoderMask.transformer_final_attn_token_to_img.v_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.v_proj.weight", new long[] { encoderOutChans, encoderOutChans / 2 }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_final_attn_token_to_img.v_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.v_proj.bias");
model.decoderMask.transformer_final_attn_token_to_img.out_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.out_proj.weight", new long[] { encoderOutChans / 2, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.transformer_final_attn_token_to_img.out_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.final_attn_token_to_image.out_proj.bias");
model.decoderMask.transformer_norm_final_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.norm_final_attn.weight");
model.decoderMask.transformer_norm_final_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.transformer.norm_final_attn.bias");
model.decoderMask.output_upscaling_0_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.output_upscaling.0.weight", new long[] { 2, 2, imgEmbdCount, encoderOutChans }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.output_upscaling_0_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.output_upscaling.0.bias");
model.decoderMask.output_upscaling_1_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.output_upscaling.1.weight");
model.decoderMask.output_upscaling_1_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.output_upscaling.1.bias");
model.decoderMask.output_upscaling_3_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.output_upscaling.3.weight", new long[] { 2, 2, imgEmbdCount / 2, imgEmbdCount }, Structs.GGmlType.GGML_TYPE_F16);
model.decoderMask.output_upscaling_3_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.output_upscaling.3.bias");
int n_hypernet_mpls_count = 4;
model.decoderMask.output_hypernet_mlps = new SamLayerDecOutputHypernetMlps[n_hypernet_mpls_count];
for (int i = 0; i < n_hypernet_mpls_count; ++i)
{
string prefix = "mask_decoder.output_hypernetworks_mlps." + i + ".";
model.decoderMask.output_hypernet_mlps[i].w_0 = GetTensorFromName(context, modelLoader, tensors, prefix + "layers.0.weight");
model.decoderMask.output_hypernet_mlps[i].b_0 = GetTensorFromName(context, modelLoader, tensors, prefix + "layers.0.bias");
model.decoderMask.output_hypernet_mlps[i].w_1 = GetTensorFromName(context, modelLoader, tensors, prefix + "layers.1.weight");
model.decoderMask.output_hypernet_mlps[i].b_1 = GetTensorFromName(context, modelLoader, tensors, prefix + "layers.1.bias");
model.decoderMask.output_hypernet_mlps[i].w_2 = GetTensorFromName(context, modelLoader, tensors, prefix + "layers.2.weight", new long[] { encoderOutChans, imgEmbdCount / 2 });
model.decoderMask.output_hypernet_mlps[i].b_2 = GetTensorFromName(context, modelLoader, tensors, prefix + "layers.2.bias");
}
model.decoderMask.iou_prediction_head_0_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_prediction_head.layers.0.weight");
model.decoderMask.iou_prediction_head_0_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_prediction_head.layers.0.bias");
model.decoderMask.iou_prediction_head_1_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_prediction_head.layers.1.weight");
model.decoderMask.iou_prediction_head_1_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_prediction_head.layers.1.bias");
model.decoderMask.iou_prediction_head_2_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_prediction_head.layers.2.weight", new long[] { encoderOutChans, ptEmbd });
model.decoderMask.iou_prediction_head_2_b = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_prediction_head.layers.2.bias");
model.decoderMask.iou_token_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.iou_token.weight", new long[] { encoderOutChans, 1 });
model.decoderMask.mask_tokens_w = GetTensorFromName(context, modelLoader, tensors, "mask_decoder.mask_tokens.weight", new long[] { encoderOutChans, ptEmbd });
}
return model;
}
static SafeGGmlTensor GetTensorFromName(SafeGGmlContext context, PickleLoader loader, List<Tensor> tensors, string name, Structs.GGmlType type = Structs.GGmlType.GGML_TYPE_F32)
{
var tensor = tensors.Find(x => x.Name == name);
if (tensor == null)
{
throw new Exception($"tensor {name} not found");
}
byte[] bytes = loader.ReadByteFromFile(tensor);
bytes = TransData(bytes, tensor.Type, type);
long[] ne = new long[tensor.Shape.Count];
for (int i = 0; i < tensor.Shape.Count; i++)
{
ne[i] = (long)tensor.Shape[i];
}
SafeGGmlTensor t = context.NewTensor(type, ne);
t.SetData(bytes);
t.Name = tensor.Name;
return t;
}
static SafeGGmlTensor GetTensorFromName(SafeGGmlContext context, ModelLoader.PickleLoader loader, List<ModelLoader.Tensor> tensors, string name, long[] shape, Structs.GGmlType type = Structs.GGmlType.GGML_TYPE_F32)
{
if (shape == null)
{
throw new ArgumentException("Shape is empty");
}
if (shape.Length < 0 || shape.Length > 4)
{
throw new ArgumentException("Shape is out of range");
}
var tensor = tensors.Find(x => x.Name == name);
if (tensor == null)
{
throw new Exception($"tensor {name} not found");
}
ulong orgShapeMut = 1;
foreach (ulong a in tensor.Shape)
{
orgShapeMut *= a;
};
ulong desShapeMut = 1;
foreach (ulong a in shape)
{
desShapeMut *= a;
}
if (orgShapeMut != desShapeMut)
{
throw new Exception("Shape not same");
}
byte[] bytes = loader.ReadByteFromFile(tensor);
bytes = TransData(bytes, tensor.Type, type);
SafeGGmlTensor t = context.NewTensor(type, shape);
t.SetData(bytes);
t.Name = tensor.Name;
return t;
}
static byte[] TransData(byte[] data, Structs.GGmlType srcType, Structs.GGmlType desType)
{
if (srcType == desType)
{
return data;
}
if (srcType != Structs.GGmlType.GGML_TYPE_F16 && srcType != Structs.GGmlType.GGML_TYPE_BF16 && srcType != Structs.GGmlType.GGML_TYPE_F32)
{
throw new ArgumentException("Src Type not support");
}
if (desType != Structs.GGmlType.GGML_TYPE_F16 && desType != Structs.GGmlType.GGML_TYPE_BF16 && desType != Structs.GGmlType.GGML_TYPE_F32)
{
throw new ArgumentException("Des Type not support");
}
if (srcType == Structs.GGmlType.GGML_TYPE_BF16)
{
if (desType == Structs.GGmlType.GGML_TYPE_F16)
{
GGMLSharp.DataConverter.Bf16ToFp16Bytes(data);
return data;
}
else if (desType == Structs.GGmlType.GGML_TYPE_F32)
{
GGMLSharp.DataConverter.Bf16ToFp32Bytes(ref data);
return data;
}
}
else if (srcType == Structs.GGmlType.GGML_TYPE_F32)
{
if (desType == Structs.GGmlType.GGML_TYPE_BF16)
{
GGMLSharp.DataConverter.Fp32ToBf16Bytes(data);
}
else if (desType == Structs.GGmlType.GGML_TYPE_F16)
{
GGMLSharp.DataConverter.Fp32ToFp16Bytes(data);
}
return data;
}
else if (srcType == Structs.GGmlType.GGML_TYPE_F16)
{
if (desType == Structs.GGmlType.GGML_TYPE_F32)
{
GGMLSharp.DataConverter.Fp16ToFp32Bytes(ref data);
return data;
}
}
throw new ArgumentException("Not support!");
}
struct PromptEncoderResult
{
public SafeGGmlTensor embdPromptSparse;
public SafeGGmlTensor embdPromptDense;
};
static SafeGGmlTensor SamFillDensePe(SamModel model, SafeGGmlContext ctx0, SafeGGmlGraph gf, SamState state)
{
SamHparams hparams = model.hparams;
SamEncoderPrompt enc = model.encoderPrompt;
int n_img_embd = hparams.ImgEmbdCount;
SafeGGmlTensor xy_embed_stacked = ctx0.NewTensor3d(Structs.GGmlType.GGML_TYPE_F32, 2, n_img_embd, n_img_embd);
xy_embed_stacked.Name = "xy_embed_stacked";
xy_embed_stacked.SetInput();
SafeGGmlTensor cur = ctx0.MulMat(ctx0.Cont(ctx0.Transpose(enc.pe)), xy_embed_stacked);
cur = ctx0.Scale(cur, 2.0f * (float)Math.PI);
// concat
// ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L192
{
SafeGGmlTensor t_sin = ctx0.MapCustom1(cur, opSin, GGML_N_TASKS_MAX, IntPtr.Zero);
SafeGGmlTensor t_cos = ctx0.MapCustom1(cur, opCos, GGML_N_TASKS_MAX, IntPtr.Zero);
cur = ctx0.NewTensor3d(Structs.GGmlType.GGML_TYPE_F32, t_sin.Shape[0] + t_cos.Shape[0], cur.Shape[1], cur.Shape[2]);
gf.BuildForwardExpend(ctx0.Copy(t_sin, ctx0.View3d(cur, t_sin.Shape[0], t_sin.Shape[1], t_sin.Shape[2], cur.Stride[1], cur.Stride[2], 0)));
gf.BuildForwardExpend(ctx0.Copy(t_cos, ctx0.View3d(cur, t_sin.Shape[0], t_sin.Shape[1], t_sin.Shape[2], cur.Stride[1], cur.Stride[2], t_sin.Stride[1])));
}
SafeGGmlTensor pe_img_dense = ctx0.Cont(ctx0.Permute(cur, 2, 0, 1, 3));
gf.BuildForwardExpend(pe_img_dense);
return pe_img_dense;
}
static PromptEncoderResult SamEncodePrompt(SamModel model, SafeGGmlContext ctx0, SafeGGmlGraph gf, SamState state)
{
SamHparams hparams = model.hparams;
SamEncoderPrompt enc = model.encoderPrompt;
SafeGGmlTensor inp = ctx0.NewTensor2d(Structs.GGmlType.GGML_TYPE_F32, 2, 2);
inp.Name = "prompt_input";
inp.SetInput();
SafeGGmlTensor cur = ctx0.MulMat(ctx0.Cont(ctx0.Transpose(enc.pe)), inp);
cur = ctx0.Scale(cur, 2.0f * (float)Math.PI);
// concat
// ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L192
{
SafeGGmlTensor t_sin = ctx0.MapCustom1(cur, opSin, GGML_N_TASKS_MAX, IntPtr.Zero);
SafeGGmlTensor t_cos = ctx0.MapCustom1(cur, opCos, GGML_N_TASKS_MAX, IntPtr.Zero);
cur = ctx0.NewTensor2d(Structs.GGmlType.GGML_TYPE_F32, t_sin.Shape[0] + t_cos.Shape[0], cur.Shape[1]);
gf.BuildForwardExpend(ctx0.Copy(t_sin, ctx0.View2d(cur, t_sin.Shape[0], t_sin.Shape[1], cur.Stride[1], 0)));
gf.BuildForwardExpend(ctx0.Copy(t_cos, ctx0.View2d(cur, t_sin.Shape[0], t_sin.Shape[1], cur.Stride[1], t_sin.Stride[1])));
// overwrite label == -1 with not_a_point_embed.weight
// ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L86
// TODO: extend for multiple points
gf.BuildForwardExpend(ctx0.Copy(enc.not_a_pt_embd_w, ctx0.View2d(cur, cur.Shape[0], 1, cur.Stride[1], cur.Stride[1])));
}
// add point_embeddings[1] to label == 1
// ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/prompt_encoder.py#L90
SafeGGmlTensor v = ctx0.View2d(cur, cur.Shape[0], 1, cur.Stride[1], 0);
gf.BuildForwardExpend(ctx0.Copy(ctx0.AddInplace(v, enc.pt_embd[1]), v));
SafeGGmlTensor embd_prompt_sparse = cur;
gf.BuildForwardExpend(embd_prompt_sparse);
SafeGGmlTensor embd_prompt_dense = ctx0.Repeat(
ctx0.Cont(
ctx0.View3d(enc.no_mask_embd_w,
1, 1, enc.no_mask_embd_w.Shape[0], enc.no_mask_embd_w.Stride[0], enc.no_mask_embd_w.Stride[0], 0)),
ctx0.NewTensor3d(Structs.GGmlType.GGML_TYPE_F32, hparams.ImgEmbdCount, hparams.ImgEmbdCount, hparams.EncoderOutChans));
gf.BuildForwardExpend(embd_prompt_dense);
//printf("used_mem = %zu\n", ggml_used_mem(ctx0));
PromptEncoderResult res;
res.embdPromptSparse = embd_prompt_sparse;
res.embdPromptDense = embd_prompt_dense;
return res;
}
static SafeGGmlTensor SamDecodeMaskMlpRelu3(SafeGGmlContext ctx0, SafeGGmlTensor input, SafeGGmlTensor w0, SafeGGmlTensor b0, SafeGGmlTensor w1, SafeGGmlTensor b1, SafeGGmlTensor w2, SafeGGmlTensor b2)
{
SafeGGmlTensor cur = ctx0.Linear(input, w0, b0);
cur = ctx0.Relu(cur);
cur = ctx0.Linear(cur, w1, b1);
cur = ctx0.Relu(cur);
cur = ctx0.Linear(cur, w2, b2);
return cur;
}
static bool SamDecodeMask(SamModel model, PromptEncoderResult prompt, SafeGGmlTensor pe_img, SafeGGmlContext ctx0, SafeGGmlGraph gf, SamState state)
{
SamHparams hparams = model.hparams;
SamDecoderMask dec = model.decoderMask;
int n_img_embd = hparams.ImgEmbdCount;
SafeGGmlTensor tokens;
{
// Concatenate output tokens
// ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L120
SafeGGmlTensor sparse = prompt.embdPromptSparse;
tokens = ctx0.NewTensor3d(Structs.GGmlType.GGML_TYPE_F32, dec.iou_token_w.Shape[0], dec.iou_token_w.Shape[1] + dec.mask_tokens_w.Shape[1] + sparse.Shape[1], sparse.Shape[2]);
ulong[] offsets = { 0, (ulong)dec.iou_token_w.Shape[1] * tokens.Stride[1], (ulong)dec.iou_token_w.Shape[1] * tokens.Stride[1] + (ulong)dec.mask_tokens_w.Shape[1] * tokens.Stride[1] };
gf.BuildForwardExpend(ctx0.Copy(dec.iou_token_w, ctx0.View2d(tokens, tokens.Shape[0], dec.iou_token_w.Shape[1], tokens.Stride[1], offsets[0])));
gf.BuildForwardExpend(ctx0.Copy(dec.mask_tokens_w, ctx0.View2d(tokens, tokens.Shape[0], dec.mask_tokens_w.Shape[1], tokens.Stride[1], offsets[1])));
gf.BuildForwardExpend(ctx0.Copy(sparse, ctx0.View2d(tokens, tokens.Shape[0], sparse.Shape[1], tokens.Stride[1], offsets[2])));
// TODO: Sparse prompt embeddings can have more than one Point
}
SafeGGmlTensor src;
SafeGGmlTensor posSrc;
long[] srcNE = { 0, 0, 0, 0 };
{
// Expand per-image Data in the batch direction to be per-mask
// ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/mask_decoder.py#L125
src = ctx0.NewTensor4d(Structs.GGmlType.GGML_TYPE_F32, state.embdImg.Shape[0], state.embdImg.Shape[1], state.embdImg.Shape[2], tokens.Shape[2]);
src = ctx0.Add(
ctx0.Repeat(
state.embdImg,
src),
prompt.embdPromptDense);
srcNE[0] = src.Shape[0];
srcNE[1] = src.Shape[1];
srcNE[2] = src.Shape[2];
srcNE[3] = src.Shape[3];
// flatten & permute
// ref: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/transformer.py#L83
src = ctx0.Cont(ctx0.Permute(
ctx0.View3d(
src,
src.Shape[0] * src.Shape[1],
src.Shape[2],