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 / convert-pth-to-ggml.py

147 lines · 3910 bytes Raw Blame History
1# Convert a SAM model checkpoint to a ggml compatible file
2#
3
4import sys
5import torch
6import struct
7import numpy as np
8
9if len(sys.argv) < 3:
10 print("Usage: convert-pth-to-ggml.py file-model dir-output [ftype]\n")
11 print(" ftype == 0 -> float32")
12 print(" ftype == 1 -> float16")
13 sys.exit(1)
14
15# output in the same directory as the model
16fname_model = sys.argv[1]
17dir_out = sys.argv[2]
18fname_out = dir_out + "/ggml-model.bin"
19
20# possible data types
21# ftype == 0 -> float32
22# ftype == 1 -> float16
23#
24# map from ftype to string
25ftype_str = ["f32", "f16"]
26
27ftype = 1
28if len(sys.argv) > 3:
29 ftype = int(sys.argv[3])
30
31if ftype < 0 or ftype > 1:
32 print("Invalid ftype: " + str(ftype))
33 sys.exit(1)
34
35fname_out = fname_out.replace(".bin", "-" + ftype_str[ftype] + ".bin")
36
37# Default params are set to sam_vit_b checkpoint
38n_enc_state = 768
39n_enc_layers = 12
40n_enc_heads = 12
41n_enc_out_chans = 256
42n_pt_embd = 4
43
44model = torch.load(fname_model, map_location="cpu")
45for k, v in model.items():
46 print(k, v.shape)
47 if k == "image_encoder.blocks.0.norm1.weight":
48 n_enc_state = v.shape[0]
49
50if n_enc_state == 1024: # sam_vit_l
51 n_enc_layers = 24
52 n_enc_heads = 16
53elif n_enc_state == 1280: # sam_vit_h
54 n_enc_layers = 32
55 n_enc_heads = 16
56
57hparams = {
58 "n_enc_state": n_enc_state,
59 "n_enc_layers": n_enc_layers,
60 "n_enc_heads": n_enc_heads,
61 "n_enc_out_chans": n_enc_out_chans,
62 "n_pt_embd": n_pt_embd,
63}
64
65print(hparams)
66
67for k, v in model.items():
68 print(k, v.shape)
69
70#exit()
71#code.interact(local=locals())
72
73fout = open(fname_out, "wb")
74
75fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex
76fout.write(struct.pack("i", hparams["n_enc_state"]))
77fout.write(struct.pack("i", hparams["n_enc_layers"]))
78fout.write(struct.pack("i", hparams["n_enc_heads"]))
79fout.write(struct.pack("i", hparams["n_enc_out_chans"]))
80fout.write(struct.pack("i", hparams["n_pt_embd"]))
81fout.write(struct.pack("i", ftype))
82
83for k, v in model.items():
84 name = k
85 shape = v.shape
86
87 if name[:19] == "prompt_encoder.mask":
88 continue
89
90 print("Processing variable: " + name + " with shape: ", shape, " and type: ", v.dtype)
91
92 #data = tf.train.load_variable(dir_model, name).squeeze()
93 #data = v.numpy().squeeze()
94 data = v.numpy()
95 n_dims = len(data.shape)
96
97 # for efficiency - transpose some matrices
98 # "model/h.*/attn/c_attn/w"
99 # "model/h.*/attn/c_proj/w"
100 # "model/h.*/mlp/c_fc/w"
101 # "model/h.*/mlp/c_proj/w"
102 #if name[-14:] == "/attn/c_attn/w" or \
103 # name[-14:] == "/attn/c_proj/w" or \
104 # name[-11:] == "/mlp/c_fc/w" or \
105 # name[-13:] == "/mlp/c_proj/w":
106 # print(" Transposing")
107 # data = data.transpose()
108
109 dshape = data.shape
110
111 # default type is fp16
112 ftype_cur = 1
113 if ftype == 0 or n_dims == 1 or \
114 name == "image_encoder.pos_embed" or \
115 name.startswith("prompt_encoder") or \
116 name.startswith("mask_decoder.iou_token") or \
117 name.startswith("mask_decoder.mask_tokens"):
118 print(" Converting to float32")
119 data = data.astype(np.float32)
120 ftype_cur = 0
121 else:
122 print(" Converting to float16")
123 data = data.astype(np.float16)
124
125 # reshape the 1D bias into a 4D tensor so we can use ggml_repeat
126 # keep it in F32 since the data is small
127 if name == "image_encoder.patch_embed.proj.bias":
128 data = data.reshape(1, data.shape[0], 1, 1)
129 n_dims = len(data.shape)
130 dshape = data.shape
131
132 print(" New shape: ", dshape)
133
134 # header
135 str = name.encode('utf-8')
136 fout.write(struct.pack("iii", n_dims, len(str), ftype_cur))
137 for i in range(n_dims):
138 fout.write(struct.pack("i", dshape[n_dims - 1 - i]))
139 fout.write(str)
140
141 # data
142 data.tofile(fout)
143
144fout.close()
145
146print("Done. Output file: " + fname_out)
147print("")