convert-h5-to-ggml.py 6.3 KB

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