ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / examples / gpt-2 / convert-h5-to-ggml.py
| 1 | # Convert GPT-2 h5 transformer model to ggml format |
| 2 | # |
| 3 | # Load the model using GPT2Model. |
| 4 | # Iterate over all variables and write them to a binary file. |
| 5 | # |
| 6 | # For each variable, write the following: |
| 7 | # - Number of dimensions (int) |
| 8 | # - Name length (int) |
| 9 | # - Dimensions (int[n_dims]) |
| 10 | # - Name (char[name_length]) |
| 11 | # - Data (float[n_dims]) |
| 12 | # |
| 13 | # By default, the bigger matrices are converted to 16-bit floats. |
| 14 | # This can be disabled by adding the "use-f32" CLI argument. |
| 15 | # |
| 16 | # At the start of the ggml file we write the model parameters |
| 17 | # and vocabulary. |
| 18 | # |
| 19 | |
| 20 | import sys |
| 21 | import struct |
| 22 | import json |
| 23 | import numpy as np |
| 24 | import re |
| 25 | |
| 26 | from transformers import GPT2Model |
| 27 | |
| 28 | # ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py |
| 29 | def bytes_to_unicode(): |
| 30 | """ |
| 31 | Returns list of utf-8 byte and a corresponding list of unicode strings. |
| 32 | The reversible bpe codes work on unicode strings. |
| 33 | This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. |
| 34 | When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. |
| 35 | This is a signficant percentage of your normal, say, 32K bpe vocab. |
| 36 | To avoid that, we want lookup tables between utf-8 bytes and unicode strings. |
| 37 | And avoids mapping to whitespace/control characters the bpe code barfs on. |
| 38 | """ |
| 39 | bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) |
| 40 | cs = bs[:] |
| 41 | n = 0 |
| 42 | for b in range(2**8): |
| 43 | if b not in bs: |
| 44 | bs.append(b) |
| 45 | cs.append(2**8+n) |
| 46 | n += 1 |
| 47 | cs = [chr(n) for n in cs] |
| 48 | return dict(zip(bs, cs)) |
| 49 | |
| 50 | if len(sys.argv) < 2: |
| 51 | print("Usage: convert-h5-to-ggml.py dir-model [use-f32]\n") |
| 52 | sys.exit(1) |
| 53 | |
| 54 | # output in the same directory as the model |
| 55 | dir_model = sys.argv[1] |
| 56 | fname_out = sys.argv[1] + "/ggml-model.bin" |
| 57 | |
| 58 | with open(dir_model + "/vocab.json", "r", encoding="utf-8") as f: |
| 59 | encoder = json.load(f) |
| 60 | |
| 61 | with open(dir_model + "/added_tokens.json", "r", encoding="utf-8") as f: |
| 62 | encoder_added = json.load(f) |
| 63 | |
| 64 | with open(dir_model + "/config.json", "r", encoding="utf-8") as f: |
| 65 | hparams = json.load(f) |
| 66 | |
| 67 | # use 16-bit or 32-bit floats |
| 68 | use_f16 = True |
| 69 | if len(sys.argv) > 2: |
| 70 | use_f16 = False |
| 71 | fname_out = sys.argv[1] + "/ggml-model-f32.bin" |
| 72 | |
| 73 | model = GPT2Model.from_pretrained(dir_model, low_cpu_mem_usage=True) |
| 74 | #print (model) |
| 75 | |
| 76 | list_vars = model.state_dict() |
| 77 | #print (list_vars) |
| 78 | |
| 79 | fout = open(fname_out, "wb") |
| 80 | |
| 81 | fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex |
| 82 | fout.write(struct.pack("i", hparams["vocab_size"])) |
| 83 | fout.write(struct.pack("i", hparams["n_positions"])) |
| 84 | fout.write(struct.pack("i", hparams["n_embd"])) |
| 85 | fout.write(struct.pack("i", hparams["n_head"])) |
| 86 | fout.write(struct.pack("i", hparams["n_layer"])) |
| 87 | #fout.write(struct.pack("i", hparams["rotary_dim"])) |
| 88 | fout.write(struct.pack("i", use_f16)) |
| 89 | |
| 90 | byte_encoder = bytes_to_unicode() |
| 91 | byte_decoder = {v:k for k, v in byte_encoder.items()} |
| 92 | |
| 93 | fout.write(struct.pack("i", len(encoder) + len(encoder_added))) |
| 94 | |
| 95 | for key in encoder: |
| 96 | text = bytearray([byte_decoder[c] for c in key]) |
| 97 | fout.write(struct.pack("i", len(text))) |
| 98 | fout.write(text) |
| 99 | |
| 100 | for key in encoder_added: |
| 101 | text = bytearray([byte_decoder[c] for c in key]) |
| 102 | fout.write(struct.pack("i", len(text))) |
| 103 | fout.write(text) |
| 104 | |
| 105 | for name in list_vars.keys(): |
| 106 | data = list_vars[name].squeeze().numpy() |
| 107 | print("Processing variable: " + name + " with shape: ", data.shape) |
| 108 | |
| 109 | # we don't need these |
| 110 | if name.endswith("attn.masked_bias") or name.endswith(".attn.bias"): |
| 111 | print(" Skipping variable: " + name) |
| 112 | continue |
| 113 | |
| 114 | n_dims = len(data.shape); |
| 115 | |
| 116 | # ftype == 0 -> float32, ftype == 1 -> float16 |
| 117 | ftype = 0; |
| 118 | if use_f16: |
| 119 | if name[-7:] == ".weight" and n_dims == 2: |
| 120 | print(" Converting to float16") |
| 121 | data = data.astype(np.float16) |
| 122 | ftype = 1 |
| 123 | else: |
| 124 | print(" Converting to float32") |
| 125 | data = data.astype(np.float32) |
| 126 | ftype = 0 |
| 127 | |
| 128 | # for efficiency - transpose these matrices: |
| 129 | # "transformer.h.*.mlp.c_proj.weight |
| 130 | if name.endswith(".mlp.c_proj.weight"): |
| 131 | print(" Transposing") |
| 132 | data = data.transpose() |
| 133 | |
| 134 | # rename headers to keep compatibility |
| 135 | if name == "ln_f.weight": |
| 136 | name = "model/ln_f/g" |
| 137 | elif name == "ln_f.bias": |
| 138 | name = "model/ln_f/b" |
| 139 | elif name == "wte.weight": |
| 140 | name = "model/wte" |
| 141 | elif name == "wpe.weight": |
| 142 | name = "model/wpe" |
| 143 | elif re.match(r"h\.\d+\.ln_1\.weight", name): |
| 144 | i = re.findall("\d+", name)[0] |
| 145 | name = f"model/h{i}/ln_1/g" |
| 146 | elif re.match(r"h\.\d+\.ln_1\.bias", name): |
| 147 | i = re.findall("\d+", name)[0] |
| 148 | name = f"model/h{i}/ln_1/b" |
| 149 | elif re.match(r"h\.\d+\.attn\.c_attn\.weight", name): |
| 150 | i = re.findall("\d+", name)[0] |
| 151 | name = f"model/h{i}/attn/c_attn/w" |
| 152 | elif re.match(r"h\.\d+\.attn\.c_attn\.bias", name): |
| 153 | i = re.findall("\d+", name)[0] |
| 154 | name = f"model/h{i}/attn/c_attn/b" |
| 155 | elif re.match(r"h\.\d+\.attn\.c_proj\.weight", name): |
| 156 | i = re.findall("\d+", name)[0] |
| 157 | name = f"model/h{i}/attn/c_proj/w" |
| 158 | elif re.match(r"h.\d+.attn.c_proj.bias", name): |
| 159 | i = re.findall("\d+", name)[0] |
| 160 | name = f"model/h{i}/attn/c_proj/b" |
| 161 | elif re.match(r"h.\d+.ln_2.weight", name): |
| 162 | i = re.findall("\d+", name)[0] |
| 163 | name = f"model/h{i}/ln_2/g" |
| 164 | elif re.match(r"h.\d+.ln_2.bias", name): |
| 165 | i = re.findall("\d+", name)[0] |
| 166 | name = f"model/h{i}/ln_2/b" |
| 167 | elif re.match(r"h.\d+.mlp.c_fc.weight", name): |
| 168 | i = re.findall("\d+", name)[0] |
| 169 | name = f"model/h{i}/mlp/c_fc/w" |
| 170 | elif re.match(r"h.\d+.mlp.c_fc.bias", name): |
| 171 | i = re.findall("\d+", name)[0] |
| 172 | name = f"model/h{i}/mlp/c_fc/b" |
| 173 | elif re.match(r"h.\d+.mlp.c_proj.weight", name): |
| 174 | i = re.findall("\d+", name)[0] |
| 175 | name = f"model/h{i}/mlp/c_proj/w" |
| 176 | elif re.match(r"h.\d+.mlp.c_proj.bias", name): |
| 177 | i = re.findall("\d+", name)[0] |
| 178 | name = f"model/h{i}/mlp/c_proj/b" |
| 179 | else: |
| 180 | print("Unrecognized variable name. %s", name) |
| 181 | |
| 182 | str = name.encode('utf-8') |
| 183 | |
| 184 | fout.write(struct.pack("iii", n_dims, len(str), ftype)) |
| 185 | for i in range(n_dims): |
| 186 | fout.write(struct.pack("i", data.shape[n_dims - 1 - i])) |
| 187 | fout.write(str); |
| 188 | |
| 189 | # data |
| 190 | data.tofile(fout) |
| 191 | |
| 192 | fout.close() |
| 193 | |
| 194 | print("Done. Output file: " + fname_out) |
| 195 | print("") |