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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. added_vocab = tokenizer.get_added_vocab()
  100. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
  101. for i in range(vocab_size):
  102. if i not in reverse_vocab:
  103. tokens.append(f"[PAD{i}]")
  104. toktypes.append(gguf.TokenType.USER_DEFINED)
  105. elif reverse_vocab[i] in added_vocab:
  106. tokens.append(reverse_vocab[i])
  107. if tokenizer.added_tokens_decoder[i].special:
  108. toktypes.append(gguf.TokenType.CONTROL)
  109. else:
  110. toktypes.append(gguf.TokenType.USER_DEFINED)
  111. else:
  112. tokens.append(reverse_vocab[i])
  113. toktypes.append(gguf.TokenType.NORMAL)
  114. gguf_writer.add_token_list(tokens)
  115. gguf_writer.add_token_types(toktypes)
  116. special_vocab = gguf.SpecialVocab(dir_model, load_merges = True, n_vocab = len(tokens))
  117. special_vocab.add_to_gguf(gguf_writer)
  118. # TENSORS
  119. tensor_map = gguf.get_tensor_name_map(ARCH,block_count)
  120. # tensor info
  121. print("gguf: get tensor metadata")
  122. if num_parts == 0:
  123. part_names = iter(("pytorch_model.bin",))
  124. else:
  125. part_names = (
  126. f"pytorch_model-{n:05}-of-{num_parts:05}.bin" for n in range(1, num_parts + 1)
  127. )
  128. for part_name in part_names:
  129. if args.vocab_only:
  130. break
  131. print("gguf: loading model part '" + part_name + "'")
  132. model_part = torch.load(f"{dir_model}/{part_name}", map_location="cpu")
  133. for name in model_part.keys():
  134. data = model_part[name]
  135. old_dtype = data.dtype
  136. # convert any unsupported data types to float32
  137. if data.dtype != torch.float16 and data.dtype != torch.float32:
  138. data = data.to(torch.float32)
  139. data = data.squeeze().numpy()
  140. # map tensor names
  141. new_name = tensor_map.get_name(name, try_suffixes = (".weight", ".bias"))
  142. if new_name is None:
  143. print("Cannot map tensor '" + name + "'")
  144. continue # for the sake of compatibility with some old published models, don't quit
  145. sys.exit()
  146. n_dims = len(data.shape)
  147. data_dtype = data.dtype
  148. # if f32 desired, convert any float16 to float32
  149. if ftype == 0 and data_dtype == np.float16:
  150. data = data.astype(np.float32)
  151. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  152. if ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  153. data = data.astype(np.float32)
  154. # if f16 desired, convert any float32 2-dim weight tensors to float16
  155. if ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  156. data = data.astype(np.float16)
  157. print(new_name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype))
  158. gguf_writer.add_tensor(new_name, data)
  159. # note: MPT output is tied to (same as) wte in original model;
  160. # for easier implementation in llama.cpp it's duplicated in GGUF, though :/
  161. if new_name == "token_embd.weight":
  162. gguf_writer.add_tensor("output.weight", data)
  163. print("gguf: write header")
  164. gguf_writer.write_header_to_file()
  165. print("gguf: write metadata")
  166. gguf_writer.write_kv_data_to_file()
  167. if not args.vocab_only:
  168. print("gguf: write tensors")
  169. gguf_writer.write_tensors_to_file()
  170. gguf_writer.close()
  171. print(f"gguf: model successfully exported to '{fname_out}'")
  172. print("")