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-ckpt-to-ggml.py
| 1 | # Convert a model checkpoint to a ggml compatible file |
| 2 | # |
| 3 | # Load the model using TensorFlow. |
| 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 json |
| 22 | import struct |
| 23 | import numpy as np |
| 24 | import tensorflow as tf |
| 25 | |
| 26 | # ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py |
| 27 | def bytes_to_unicode(): |
| 28 | """ |
| 29 | Returns list of utf-8 byte and a corresponding list of unicode strings. |
| 30 | The reversible bpe codes work on unicode strings. |
| 31 | This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. |
| 32 | When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. |
| 33 | This is a signficant percentage of your normal, say, 32K bpe vocab. |
| 34 | To avoid that, we want lookup tables between utf-8 bytes and unicode strings. |
| 35 | And avoids mapping to whitespace/control characters the bpe code barfs on. |
| 36 | """ |
| 37 | bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) |
| 38 | cs = bs[:] |
| 39 | n = 0 |
| 40 | for b in range(2**8): |
| 41 | if b not in bs: |
| 42 | bs.append(b) |
| 43 | cs.append(2**8+n) |
| 44 | n += 1 |
| 45 | cs = [chr(n) for n in cs] |
| 46 | return dict(zip(bs, cs)) |
| 47 | |
| 48 | # helper method to convert a numpy array to different float types |
| 49 | def convert_to_ftype(data, ftype): |
| 50 | # fp16 |
| 51 | if ftype == 1: |
| 52 | return data.astype(np.float16) |
| 53 | |
| 54 | assert False, "Invalid ftype: " + str(ftype) |
| 55 | |
| 56 | if len(sys.argv) < 3: |
| 57 | print("Usage: convert-ckpt-to-ggml.py dir-model ftype\n") |
| 58 | print(" ftype == 0 -> float32") |
| 59 | print(" ftype == 1 -> float16") |
| 60 | sys.exit(1) |
| 61 | |
| 62 | # output in the same directory as the model |
| 63 | dir_model = sys.argv[1] |
| 64 | fname_out = sys.argv[1] + "/ggml-model.bin" |
| 65 | |
| 66 | with open(dir_model + "/encoder.json", "r", encoding="utf-8") as f: |
| 67 | encoder = json.load(f) |
| 68 | |
| 69 | with open(dir_model + "/hparams.json", "r", encoding="utf-8") as f: |
| 70 | hparams = json.load(f) |
| 71 | |
| 72 | # possible data types |
| 73 | # ftype == 0 -> float32 |
| 74 | # ftype == 1 -> float16 |
| 75 | # |
| 76 | # map from ftype to string |
| 77 | ftype_str = ["f32", "f16"] |
| 78 | |
| 79 | ftype = 1 |
| 80 | if len(sys.argv) > 2: |
| 81 | ftype = int(sys.argv[2]) |
| 82 | if ftype < 0 or ftype > 1: |
| 83 | print("Invalid ftype: " + str(ftype)) |
| 84 | sys.exit(1) |
| 85 | fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin" |
| 86 | |
| 87 | list_vars = tf.train.list_variables(dir_model) |
| 88 | |
| 89 | fout = open(fname_out, "wb") |
| 90 | |
| 91 | fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex |
| 92 | fout.write(struct.pack("i", hparams["n_vocab"])) |
| 93 | fout.write(struct.pack("i", hparams["n_ctx"])) |
| 94 | fout.write(struct.pack("i", hparams["n_embd"])) |
| 95 | fout.write(struct.pack("i", hparams["n_head"])) |
| 96 | fout.write(struct.pack("i", hparams["n_layer"])) |
| 97 | fout.write(struct.pack("i", ftype)) |
| 98 | |
| 99 | byte_encoder = bytes_to_unicode() |
| 100 | byte_decoder = {v:k for k, v in byte_encoder.items()} |
| 101 | |
| 102 | fout.write(struct.pack("i", len(encoder))) |
| 103 | |
| 104 | for key in encoder: |
| 105 | text = bytearray([byte_decoder[c] for c in key]) |
| 106 | fout.write(struct.pack("i", len(text))) |
| 107 | fout.write(text) |
| 108 | |
| 109 | for name, shape in list_vars: |
| 110 | print("Processing variable: " + name + " with shape: ", shape) |
| 111 | |
| 112 | data = tf.train.load_variable(dir_model, name).squeeze() |
| 113 | n_dims = len(data.shape); |
| 114 | |
| 115 | # for efficiency - transpose the projection matrices |
| 116 | # "model/h.*/attn/c_attn/w" |
| 117 | # "model/h.*/attn/c_proj/w" |
| 118 | # "model/h.*/mlp/c_fc/w" |
| 119 | # "model/h.*/mlp/c_proj/w" |
| 120 | if name[-14:] == "/attn/c_attn/w" or \ |
| 121 | name[-14:] == "/attn/c_proj/w" or \ |
| 122 | name[-11:] == "/mlp/c_fc/w" or \ |
| 123 | name[-13:] == "/mlp/c_proj/w": |
| 124 | print(" Transposing") |
| 125 | data = data.transpose() |
| 126 | |
| 127 | dshape = data.shape |
| 128 | |
| 129 | ftype_cur = 0 |
| 130 | if ftype != 0: |
| 131 | # match name: |
| 132 | # "model/wte" |
| 133 | # "model/h.*/attn/c_attn/w" |
| 134 | # "model/h.*/attn/c_proj/w" |
| 135 | # "model/h.*/mlp/c_fc/w" |
| 136 | # "model/h.*/mlp/c_proj/w" |
| 137 | if name == "model/wte" or name[-2:] == "/w": |
| 138 | print(" Converting to " + ftype_str[ftype]) |
| 139 | data = convert_to_ftype(data, ftype) |
| 140 | ftype_cur = ftype |
| 141 | else: |
| 142 | print(" Converting to float32") |
| 143 | data = data.astype(np.float32) |
| 144 | ftype_cur = 0 |
| 145 | |
| 146 | # header |
| 147 | str = name.encode('utf-8') |
| 148 | fout.write(struct.pack("iii", n_dims, len(str), ftype_cur)) |
| 149 | for i in range(n_dims): |
| 150 | fout.write(struct.pack("i", dshape[n_dims - 1 - i])) |
| 151 | fout.write(str); |
| 152 | |
| 153 | # data |
| 154 | data.tofile(fout) |
| 155 | |
| 156 | fout.close() |
| 157 | |
| 158 | print("Done. Output file: " + fname_out) |
| 159 | print("") |