convert-pth-to-ggml.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # Convert a LLaMA model checkpoint to a ggml compatible file
  2. #
  3. # Load the model using Torch
  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 os
  20. import sys
  21. import json
  22. import struct
  23. import numpy as np
  24. import torch
  25. from sentencepiece import SentencePieceProcessor
  26. if len(sys.argv) < 3:
  27. print("Usage: convert-ckpt-to-ggml.py dir-model ftype\n")
  28. print(" ftype == 0 -> float32")
  29. print(" ftype == 1 -> float16")
  30. sys.exit(1)
  31. # output in the same directory as the model
  32. dir_model = sys.argv[1]
  33. fname_hparams = sys.argv[1] + "/params.json"
  34. fname_tokenizer = sys.argv[1] + "/../tokenizer.model"
  35. def get_n_parts(dim):
  36. if dim == 4096:
  37. return 1
  38. elif dim == 5120:
  39. return 2
  40. elif dim == 6656:
  41. return 4
  42. elif dim == 8192:
  43. return 8
  44. else:
  45. print("Invalid dim: " + str(dim))
  46. sys.exit(1)
  47. # possible data types
  48. # ftype == 0 -> float32
  49. # ftype == 1 -> float16
  50. #
  51. # map from ftype to string
  52. ftype_str = ["f32", "f16"]
  53. ftype = 1
  54. if len(sys.argv) > 2:
  55. ftype = int(sys.argv[2])
  56. if ftype < 0 or ftype > 1:
  57. print("Invalid ftype: " + str(ftype))
  58. sys.exit(1)
  59. fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin"
  60. if os.path.exists(fname_out):
  61. print(f"Skip conversion, it already exists: {fname_out}")
  62. sys.exit(0)
  63. with open(fname_hparams, "r") as f:
  64. hparams = json.load(f)
  65. tokenizer = SentencePieceProcessor(fname_tokenizer)
  66. hparams.update({"vocab_size": tokenizer.vocab_size()})
  67. n_parts = get_n_parts(hparams["dim"])
  68. print(hparams)
  69. print('n_parts = ', n_parts)
  70. for p in range(n_parts):
  71. print('Processing part ', p)
  72. #fname_model = sys.argv[1] + "/consolidated.00.pth"
  73. fname_model = sys.argv[1] + "/consolidated.0" + str(p) + ".pth"
  74. fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin"
  75. if (p > 0):
  76. fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin" + "." + str(p)
  77. model = torch.load(fname_model, map_location="cpu")
  78. fout = open(fname_out, "wb")
  79. fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex
  80. fout.write(struct.pack("i", hparams["vocab_size"]))
  81. fout.write(struct.pack("i", hparams["dim"]))
  82. fout.write(struct.pack("i", hparams["multiple_of"]))
  83. fout.write(struct.pack("i", hparams["n_heads"]))
  84. fout.write(struct.pack("i", hparams["n_layers"]))
  85. fout.write(struct.pack("i", hparams["dim"] // hparams["n_heads"])) # rot (obsolete)
  86. fout.write(struct.pack("i", ftype))
  87. # Is this correct??
  88. for i in range(tokenizer.vocab_size()):
  89. if tokenizer.is_unknown(i):
  90. # "<unk>" token (translated as ??)
  91. text = " \u2047 ".encode("utf-8")
  92. fout.write(struct.pack("i", len(text)))
  93. fout.write(text)
  94. elif tokenizer.is_control(i):
  95. # "<s>"/"</s>" tokens
  96. fout.write(struct.pack("i", 0))
  97. elif tokenizer.is_byte(i):
  98. # "<U+XX>" tokens (which may be invalid UTF-8)
  99. piece = tokenizer.id_to_piece(i)
  100. if len(piece) != 6:
  101. print("Invalid token: " + piece)
  102. sys.exit(1)
  103. byte_value = int(piece[3:-1], 16)
  104. fout.write(struct.pack("i", 1))
  105. fout.write(struct.pack("B", byte_value))
  106. else:
  107. # normal token. Uses U+2581 (LOWER ONE EIGHTH BLOCK) to represent spaces.
  108. text = tokenizer.id_to_piece(i).replace("\u2581", " ").encode("utf-8")
  109. fout.write(struct.pack("i", len(text)))
  110. fout.write(text)
  111. for k, v in model.items():
  112. name = k
  113. shape = v.shape
  114. # skip layers.X.attention.inner_attention.rope.freqs
  115. if name[-5:] == "freqs":
  116. continue
  117. print("Processing variable: " + name + " with shape: ", shape, " and type: ", v.dtype)
  118. #data = tf.train.load_variable(dir_model, name).squeeze()
  119. data = v.numpy().squeeze()
  120. n_dims = len(data.shape);
  121. # for efficiency - transpose some matrices
  122. # "model/h.*/attn/c_attn/w"
  123. # "model/h.*/attn/c_proj/w"
  124. # "model/h.*/mlp/c_fc/w"
  125. # "model/h.*/mlp/c_proj/w"
  126. #if name[-14:] == "/attn/c_attn/w" or \
  127. # name[-14:] == "/attn/c_proj/w" or \
  128. # name[-11:] == "/mlp/c_fc/w" or \
  129. # name[-13:] == "/mlp/c_proj/w":
  130. # print(" Transposing")
  131. # data = data.transpose()
  132. dshape = data.shape
  133. # default type is fp16
  134. ftype_cur = 1
  135. if ftype == 0 or n_dims == 1:
  136. print(" Converting to float32")
  137. data = data.astype(np.float32)
  138. ftype_cur = 0
  139. # header
  140. sname = name.encode('utf-8')
  141. fout.write(struct.pack("iii", n_dims, len(sname), ftype_cur))
  142. for i in range(n_dims):
  143. fout.write(struct.pack("i", dshape[n_dims - 1 - i]))
  144. fout.write(sname);
  145. # data
  146. data.tofile(fout)
  147. # I hope this deallocates the memory ..
  148. model = None
  149. fout.close()
  150. print("Done. Output file: " + fname_out + ", (part ", p, ")")
  151. print("")