convert-pth-to-ggml.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 argparse
  20. import sys
  21. import json
  22. import struct
  23. import numpy as np
  24. import torch
  25. from sentencepiece import SentencePieceProcessor
  26. def parse_args():
  27. parser = argparse.ArgumentParser(description='Convert a LLaMA model checkpoint to a ggml compatible file')
  28. parser.add_argument('dir_model', help='directory containing the model checkpoint')
  29. parser.add_argument('ftype', type=int, choices=[0, 1], default=1, help='file type (0: float32, 1: float16)')
  30. return parser.parse_args()
  31. def get_n_parts(dim):
  32. mappings = {4096: 1, 5120: 2, 6656: 4, 8192: 8}
  33. n_parts = mappings.get(dim)
  34. if n_parts is None:
  35. print(f"Invalid dim: {dim}")
  36. sys.exit(1)
  37. print(f"n_parts = {n_parts}\n")
  38. return n_parts
  39. def load_hparams_and_tokenizer(dir_model):
  40. fname_hparams = f"{dir_model}/params.json"
  41. fname_tokenizer = f"{dir_model}/../tokenizer.model"
  42. with open(fname_hparams, "r") as f:
  43. hparams = json.load(f)
  44. print(hparams)
  45. tokenizer = SentencePieceProcessor(fname_tokenizer)
  46. hparams.update({"vocab_size": tokenizer.vocab_size()})
  47. return hparams, tokenizer
  48. def write_header(fout, hparams, ftype):
  49. keys = ["vocab_size", "dim", "multiple_of", "n_heads", "n_layers"]
  50. values = [
  51. 0x67676d6c, # magic: ggml in hex
  52. *[hparams[key] for key in keys],
  53. hparams["dim"] // hparams["n_heads"], # rot (obsolete)
  54. ftype
  55. ]
  56. fout.write(struct.pack("i" * len(values), *values))
  57. def write_tokens(fout, tokenizer):
  58. for i in range(tokenizer.vocab_size()):
  59. if tokenizer.is_unknown(i):
  60. text = " \u2047 ".encode("utf-8")
  61. elif tokenizer.is_control(i):
  62. text = b""
  63. elif tokenizer.is_byte(i):
  64. piece = tokenizer.id_to_piece(i)
  65. if len(piece) != 6:
  66. print(f"Invalid token: {piece}")
  67. sys.exit(1)
  68. byte_value = int(piece[3:-1], 16)
  69. text = struct.pack("B", byte_value)
  70. else:
  71. text = tokenizer.id_to_piece(i).replace("\u2581", " ").encode("utf-8")
  72. fout.write(struct.pack("i", len(text)))
  73. fout.write(text)
  74. def process_and_write_variables(fout, model, ftype):
  75. for name, datao in model.items():
  76. if name.endswith("freqs"):
  77. continue
  78. shape = datao.shape
  79. print(f"Processing variable: {name} with shape: {shape} and type: {datao.dtype}")
  80. data = datao.numpy().squeeze()
  81. n_dims = len(shape)
  82. # default type is fp16
  83. ftype_cur = 1
  84. if ftype == 0 or n_dims == 1:
  85. print(" Converting to float32")
  86. data = data.astype(np.float32)
  87. ftype_cur = 0
  88. # header
  89. sname = name.encode('utf-8')
  90. fout.write(struct.pack("iii", len(data.shape), len(sname), ftype_cur))
  91. for dim in reversed(data.shape):
  92. fout.write(struct.pack("i", dim))
  93. fout.write(sname)
  94. # data output to file
  95. data.tofile(fout)
  96. def main():
  97. args = parse_args()
  98. dir_model = args.dir_model
  99. ftype = args.ftype
  100. ftype_str = ["f32", "f16"]
  101. hparams, tokenizer = load_hparams_and_tokenizer(dir_model)
  102. n_parts = get_n_parts(hparams["dim"])
  103. for p in range(n_parts):
  104. print(f"Processing part {p}\n")
  105. fname_model = f"{dir_model}/consolidated.0{p}.pth"
  106. fname_out = f"{dir_model}/ggml-model-{ftype_str[ftype]}.bin{'' if p == 0 else '.' + str(p)}"
  107. model = torch.load(fname_model, map_location="cpu")
  108. with open(fname_out, "wb") as fout:
  109. write_header(fout, hparams, ftype)
  110. write_tokens(fout, tokenizer)
  111. process_and_write_variables(fout, model, ftype)
  112. del model
  113. print(f"Done. Output file: {fname_out}, (part {p})\n")
  114. if __name__ == "__main__":
  115. main()