ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / examples / gpt-j / convert-h5-to-ggml.py
| 1 | # Convert GPT-J-6B h5 transformer model to ggml format |
| 2 | # |
| 3 | # Load the model using GPTJForCausalLM. |
| 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 torch |
| 24 | import numpy as np |
| 25 | |
| 26 | from transformers import GPTJForCausalLM |
| 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) < 3: |
| 51 | print("Usage: convert-h5-to-ggml.py dir-model [use-f32]\n") |
| 52 | print(" ftype == 0 -> float32") |
| 53 | print(" ftype == 1 -> float16") |
| 54 | sys.exit(1) |
| 55 | |
| 56 | # output in the same directory as the model |
| 57 | dir_model = sys.argv[1] |
| 58 | fname_out = sys.argv[1] + "/ggml-model.bin" |
| 59 | |
| 60 | with open(dir_model + "/vocab.json", "r", encoding="utf-8") as f: |
| 61 | encoder = json.load(f) |
| 62 | |
| 63 | with open(dir_model + "/added_tokens.json", "r", encoding="utf-8") as f: |
| 64 | encoder_added = json.load(f) |
| 65 | |
| 66 | with open(dir_model + "/config.json", "r", encoding="utf-8") as f: |
| 67 | hparams = json.load(f) |
| 68 | |
| 69 | # possible data types |
| 70 | # ftype == 0 -> float32 |
| 71 | # ftype == 1 -> float16 |
| 72 | # |
| 73 | # map from ftype to string |
| 74 | ftype_str = ["f32", "f16"] |
| 75 | |
| 76 | ftype = 1 |
| 77 | if len(sys.argv) > 2: |
| 78 | ftype = int(sys.argv[2]) |
| 79 | if ftype < 0 or ftype > 1: |
| 80 | print("Invalid ftype: " + str(ftype)) |
| 81 | sys.exit(1) |
| 82 | fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin" |
| 83 | |
| 84 | |
| 85 | model = GPTJForCausalLM.from_pretrained(dir_model, low_cpu_mem_usage=True) |
| 86 | #print (model) |
| 87 | |
| 88 | list_vars = model.state_dict() |
| 89 | #print (list_vars) |
| 90 | |
| 91 | fout = open(fname_out, "wb") |
| 92 | |
| 93 | fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex |
| 94 | fout.write(struct.pack("i", hparams["vocab_size"])) |
| 95 | fout.write(struct.pack("i", hparams["n_positions"])) |
| 96 | fout.write(struct.pack("i", hparams["n_embd"])) |
| 97 | fout.write(struct.pack("i", hparams["n_head"])) |
| 98 | fout.write(struct.pack("i", hparams["n_layer"])) |
| 99 | fout.write(struct.pack("i", hparams["rotary_dim"])) |
| 100 | fout.write(struct.pack("i", ftype)) |
| 101 | |
| 102 | byte_encoder = bytes_to_unicode() |
| 103 | byte_decoder = {v:k for k, v in byte_encoder.items()} |
| 104 | |
| 105 | fout.write(struct.pack("i", len(encoder) + len(encoder_added))) |
| 106 | |
| 107 | for key in encoder: |
| 108 | text = bytearray([byte_decoder[c] for c in key]) |
| 109 | fout.write(struct.pack("i", len(text))) |
| 110 | fout.write(text) |
| 111 | |
| 112 | for key in encoder_added: |
| 113 | text = bytearray([byte_decoder[c] for c in key]) |
| 114 | fout.write(struct.pack("i", len(text))) |
| 115 | fout.write(text) |
| 116 | |
| 117 | for name in list_vars.keys(): |
| 118 | data = list_vars[name].squeeze().numpy() |
| 119 | print("Processing variable: " + name + " with shape: ", data.shape) |
| 120 | |
| 121 | # we don't need these |
| 122 | if name.endswith("attn.masked_bias") or name.endswith(".attn.bias"): |
| 123 | print(" Skipping variable: " + name) |
| 124 | continue |
| 125 | |
| 126 | n_dims = len(data.shape); |
| 127 | |
| 128 | # ftype == 0 -> float32, ftype == 1 -> float16 |
| 129 | ftype_cur = 0; |
| 130 | if ftype != 0: |
| 131 | if name[-7:] == ".weight" and n_dims == 2: |
| 132 | print(" Converting to float16") |
| 133 | data = data.astype(np.float16) |
| 134 | ftype_cur = 1 |
| 135 | else: |
| 136 | print(" Converting to float32") |
| 137 | data = data.astype(np.float32) |
| 138 | ftype_cur = 0 |
| 139 | else: |
| 140 | if data.dtype != np.float32: |
| 141 | print(" Converting to float32") |
| 142 | data = data.astype(np.float32) |
| 143 | ftype_cur = 0 |
| 144 | |
| 145 | # for efficiency - transpose these matrices: |
| 146 | # (note - with latest ggml this is no longer more efficient, so disabling it) |
| 147 | # "transformer.h.*.mlp.fc_in.weight" |
| 148 | # "transformer.h.*.attn.out_proj.weight" |
| 149 | # "transformer.h.*.attn.q_proj.weight" |
| 150 | # "transformer.h.*.attn.k_proj.weight" |
| 151 | # "transformer.h.*.attn.v_proj.weight" |
| 152 | #if name.endswith(".mlp.fc_in.weight") or \ |
| 153 | # name.endswith(".attn.out_proj.weight") or \ |
| 154 | # name.endswith(".attn.q_proj.weight") or \ |
| 155 | # name.endswith(".attn.k_proj.weight") or \ |
| 156 | # name.endswith(".attn.v_proj.weight"): |
| 157 | # print(" Transposing") |
| 158 | # data = data.transpose() |
| 159 | |
| 160 | # header |
| 161 | str = name.encode('utf-8') |
| 162 | fout.write(struct.pack("iii", n_dims, len(str), ftype_cur)) |
| 163 | for i in range(n_dims): |
| 164 | fout.write(struct.pack("i", data.shape[n_dims - 1 - i])) |
| 165 | fout.write(str); |
| 166 | |
| 167 | # data |
| 168 | data.tofile(fout) |
| 169 | |
| 170 | fout.close() |
| 171 | |
| 172 | print("Done. Output file: " + fname_out) |
| 173 | print("") |