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