convert-pth-to-ggml.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 sys
  20. import json
  21. import struct
  22. import numpy as np
  23. import torch
  24. from sentencepiece import SentencePieceProcessor
  25. if len(sys.argv) < 3:
  26. print("Usage: convert-ckpt-to-ggml.py dir-model ftype\n")
  27. print(" ftype == 0 -> float32")
  28. print(" ftype == 1 -> float16")
  29. sys.exit(1)
  30. # output in the same directory as the model
  31. dir_model = sys.argv[1]
  32. fname_out = sys.argv[1] + "/ggml-model.bin"
  33. fname_hparams = sys.argv[1] + "/params.json"
  34. fname_model = sys.argv[1] + "/consolidated.00.pth"
  35. fname_tokenizer = sys.argv[1] + "/../tokenizer.model"
  36. # possible data types
  37. # ftype == 0 -> float32
  38. # ftype == 1 -> float16
  39. #
  40. # map from ftype to string
  41. ftype_str = ["f32", "f16"]
  42. ftype = 1
  43. if len(sys.argv) > 2:
  44. ftype = int(sys.argv[2])
  45. if ftype < 0 or ftype > 1:
  46. print("Invalid ftype: " + str(ftype))
  47. sys.exit(1)
  48. fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".bin"
  49. with open(fname_hparams, "r") as f:
  50. hparams = json.load(f)
  51. tokenizer = SentencePieceProcessor(fname_tokenizer)
  52. hparams.update({"vocab_size": tokenizer.vocab_size()})
  53. print(hparams)
  54. model = torch.load(fname_model, map_location="cpu")
  55. fout = open(fname_out, "wb")
  56. fout.write(struct.pack("i", 0x67676d6c)) # magic: ggml in hex
  57. fout.write(struct.pack("i", hparams["vocab_size"]))
  58. fout.write(struct.pack("i", hparams["dim"]))
  59. fout.write(struct.pack("i", hparams["multiple_of"]))
  60. fout.write(struct.pack("i", hparams["n_heads"]))
  61. fout.write(struct.pack("i", hparams["n_layers"]))
  62. fout.write(struct.pack("i", hparams["dim"] // hparams["n_heads"])) # rot (obsolete)
  63. fout.write(struct.pack("i", ftype))
  64. # Is this correct??
  65. for i in range(32000):
  66. # TODO: this is probably wrong - not sure how this tokenizer works
  67. text = tokenizer.decode([29889, i]).encode('utf-8')
  68. # remove the first byte (it's always '.')
  69. text = text[1:]
  70. fout.write(struct.pack("i", len(text)))
  71. fout.write(text)
  72. for k, v in model.items():
  73. name = k
  74. shape = v.shape
  75. # skip layers.X.attention.inner_attention.rope.freqs
  76. if name[-5:] == "freqs":
  77. continue
  78. print("Processing variable: " + name + " with shape: ", shape, " and type: ", v.dtype)
  79. #data = tf.train.load_variable(dir_model, name).squeeze()
  80. data = v.numpy().squeeze()
  81. n_dims = len(data.shape);
  82. # for efficiency - transpose some matrices
  83. # "model/h.*/attn/c_attn/w"
  84. # "model/h.*/attn/c_proj/w"
  85. # "model/h.*/mlp/c_fc/w"
  86. # "model/h.*/mlp/c_proj/w"
  87. #if name[-14:] == "/attn/c_attn/w" or \
  88. # name[-14:] == "/attn/c_proj/w" or \
  89. # name[-11:] == "/mlp/c_fc/w" or \
  90. # name[-13:] == "/mlp/c_proj/w":
  91. # print(" Transposing")
  92. # data = data.transpose()
  93. dshape = data.shape
  94. # default type is fp16
  95. ftype_cur = 1
  96. if ftype == 0 or n_dims == 1:
  97. print(" Converting to float32")
  98. data = data.astype(np.float32)
  99. ftype_cur = 0
  100. # header
  101. str = name.encode('utf-8')
  102. fout.write(struct.pack("iii", n_dims, len(str), ftype_cur))
  103. for i in range(n_dims):
  104. fout.write(struct.pack("i", dshape[n_dims - 1 - i]))
  105. fout.write(str);
  106. # data
  107. data.tofile(fout)
  108. fout.close()
  109. print("Done. Output file: " + fname_out)
  110. print("")