convert-mpt-hf-to-gguf.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #!/usr/bin/env python3
  2. # HF mpt--> gguf conversion
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import os
  7. import struct
  8. import sys
  9. from pathlib import Path
  10. from typing import Any
  11. import numpy as np
  12. import torch
  13. from transformers import AutoTokenizer # type: ignore[import]
  14. if 'NO_LOCAL_GGUF' not in os.environ:
  15. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py' / 'gguf'))
  16. import gguf
  17. def count_model_parts(dir_model: Path) -> int:
  18. num_parts = 0
  19. for filename in os.listdir(dir_model):
  20. if filename.startswith("pytorch_model-"):
  21. num_parts += 1
  22. if num_parts > 0:
  23. print("gguf: found " + str(num_parts) + " model parts")
  24. return num_parts
  25. def parse_args() -> argparse.Namespace:
  26. parser = argparse.ArgumentParser(description="Convert an MPT model to a GGML compatible file")
  27. parser.add_argument(
  28. "--vocab-only", action="store_true",
  29. help="extract only the vocab",
  30. )
  31. parser.add_argument(
  32. "--outfile", type=Path,
  33. help="path to write to; default: based on input",
  34. )
  35. parser.add_argument(
  36. "model", type=Path,
  37. help="directory containing model file, or model file itself (*.bin)",
  38. )
  39. parser.add_argument(
  40. "ftype", type=int, choices=[0, 1], default=1, nargs='?',
  41. help="output format - use 0 for float32, 1 for float16",
  42. )
  43. return parser.parse_args()
  44. args = parse_args()
  45. dir_model = args.model
  46. ftype = args.ftype
  47. if not dir_model.is_dir():
  48. print(f'Error: {args.model} is not a directory', file = sys.stderr)
  49. sys.exit(1)
  50. # possible tensor data types
  51. # ftype == 0 -> float32
  52. # ftype == 1 -> float16
  53. # map from ftype to string
  54. ftype_str = ["f32", "f16"]
  55. if args.outfile is not None:
  56. fname_out = args.outfile
  57. else:
  58. # output in the same directory as the model by default
  59. fname_out = dir_model / f'ggml-model-{ftype_str[ftype]}.gguf'
  60. print("gguf: loading model "+dir_model.name)
  61. with open(dir_model / "config.json", "r", encoding="utf-8") as f:
  62. hparams = json.load(f)
  63. if hparams["architectures"][0] != "MPTForCausalLM":
  64. print("Model architecture not supported: " + hparams["architectures"][0])
  65. sys.exit()
  66. # get number of model parts
  67. num_parts = count_model_parts(dir_model)
  68. ARCH=gguf.MODEL_ARCH.MPT
  69. gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  70. print("gguf: get model metadata")
  71. block_count = hparams["n_layers"]
  72. gguf_writer.add_name(dir_model.name)
  73. gguf_writer.add_context_length(hparams["max_seq_len"])
  74. gguf_writer.add_embedding_length(hparams["d_model"])
  75. gguf_writer.add_block_count(block_count)
  76. gguf_writer.add_feed_forward_length(4 * hparams["d_model"])
  77. gguf_writer.add_head_count(hparams["n_heads"])
  78. if kv_n_heads := hparams["attn_config"].get("kv_n_heads"):
  79. gguf_writer.add_head_count_kv(kv_n_heads)
  80. gguf_writer.add_layer_norm_eps(1e-05)
  81. if hparams["attn_config"]["clip_qkv"] is not None:
  82. gguf_writer.add_clamp_kqv(hparams["attn_config"]["clip_qkv"])
  83. gguf_writer.add_max_alibi_bias(hparams["attn_config"]["alibi_bias_max"])
  84. # TOKENIZATION
  85. print("gguf: get tokenizer metadata")
  86. tokens: list[bytearray] = []
  87. scores: list[float] = []
  88. toktypes: list[int] = []
  89. # gpt2 tokenizer
  90. gguf_writer.add_tokenizer_model("gpt2")
  91. print("gguf: get gpt2 tokenizer vocab")
  92. # MPT token embedding tensors have dimension 50432 (hparams["vocab_size"]), but
  93. # there are only 50254 (len(tokenizer.vocab)) tokens in the vocab, presumably to
  94. # accomodate some "reserved" tokens; this is causing problems down the line in
  95. # llama.cpp, so we pad the vocab with dummy tokens:
  96. vocab_size = hparams["vocab_size"]
  97. # ref: https://github.com/cmp-nct/ggllm.cpp/blob/master/falcon_convert.py
  98. tokenizer = AutoTokenizer.from_pretrained(dir_model)
  99. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
  100. for i in range(vocab_size):
  101. tokens.append(reverse_vocab[i] if i in reverse_vocab else f"[PAD{i}]")
  102. scores.append(0.0) # dummy
  103. toktypes.append(gguf.TokenType.NORMAL)
  104. gguf_writer.add_token_list(tokens)
  105. gguf_writer.add_token_scores(scores)
  106. gguf_writer.add_token_types(toktypes)
  107. special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
  108. special_vocab.add_to_gguf(gguf_writer)
  109. # TENSORS
  110. tensor_map = gguf.get_tensor_name_map(ARCH,block_count)
  111. # tensor info
  112. print("gguf: get tensor metadata")
  113. if num_parts == 0:
  114. part_names = iter(("pytorch_model.bin",))
  115. else:
  116. part_names = (
  117. f"pytorch_model-{n:05}-of-{num_parts:05}.bin" for n in range(1, num_parts + 1)
  118. )
  119. for part_name in part_names:
  120. if args.vocab_only:
  121. break
  122. print("gguf: loading model part '" + part_name + "'")
  123. model_part = torch.load(f"{dir_model}/{part_name}", map_location="cpu")
  124. for name in model_part.keys():
  125. data = model_part[name]
  126. old_dtype = data.dtype
  127. # convert any unsupported data types to float32
  128. if data.dtype != torch.float16 and data.dtype != torch.float32:
  129. data = data.to(torch.float32)
  130. data = data.squeeze().numpy()
  131. # map tensor names
  132. new_name = tensor_map.get_name(name, try_suffixes = (".weight", ".bias"))
  133. if new_name is None:
  134. print("Cannot map tensor '" + name + "'")
  135. continue # for the sake of compatibility with some old published models, don't quit
  136. sys.exit()
  137. n_dims = len(data.shape)
  138. data_dtype = data.dtype
  139. # if f32 desired, convert any float16 to float32
  140. if ftype == 0 and data_dtype == np.float16:
  141. data = data.astype(np.float32)
  142. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  143. if ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  144. data = data.astype(np.float32)
  145. # if f16 desired, convert any float32 2-dim weight tensors to float16
  146. if ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  147. data = data.astype(np.float16)
  148. print(new_name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype))
  149. gguf_writer.add_tensor(new_name, data)
  150. # note: MPT output is tied to (same as) wte in original model;
  151. # for easier implementation in llama.cpp it's duplicated in GGUF, though :/
  152. if new_name == "token_embd.weight":
  153. gguf_writer.add_tensor("output.weight", data)
  154. print("gguf: write header")
  155. gguf_writer.write_header_to_file()
  156. print("gguf: write metadata")
  157. gguf_writer.write_kv_data_to_file()
  158. if not args.vocab_only:
  159. print("gguf: write tensors")
  160. gguf_writer.write_tensors_to_file()
  161. gguf_writer.close()
  162. print(f"gguf: model successfully exported to '{fname_out}'")
  163. print("")