convert-h5-to-ggml.py 5.4 KB

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