convert-starcoder-hf-to-gguf.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #!/usr/bin/env python3
  2. # HF starcoder --> 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 bytes_to_unicode():
  18. # ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
  19. """
  20. Returns list of utf-8 byte and a corresponding list of unicode strings.
  21. The reversible bpe codes work on unicode strings.
  22. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  23. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  24. This is a significant percentage of your normal, say, 32K bpe vocab.
  25. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  26. And avoids mapping to whitespace/control characters the bpe code barfs on.
  27. """
  28. bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
  29. cs = bs[:]
  30. n = 0
  31. for b in range(2**8):
  32. if b not in bs:
  33. bs.append(b)
  34. cs.append(2**8+n)
  35. n += 1
  36. return dict(zip(bs, (chr(n) for n in cs)))
  37. def count_model_parts(dir_model: Path) -> int:
  38. num_parts = 0
  39. for filename in os.listdir(dir_model):
  40. if filename.startswith("pytorch_model-"):
  41. num_parts += 1
  42. if num_parts > 0:
  43. print("gguf: found " + str(num_parts) + " model parts")
  44. return num_parts
  45. def parse_args() -> argparse.Namespace:
  46. parser = argparse.ArgumentParser(description="Convert a StarCoder model to a GGML compatible file")
  47. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  48. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  49. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.bin)")
  50. parser.add_argument("ftype", type=int, help="output format - use 0 for float32, 1 for float16", choices=[0, 1], default = 1)
  51. return parser.parse_args()
  52. args = parse_args()
  53. dir_model = args.model
  54. ftype = args.ftype
  55. if not dir_model.is_dir():
  56. print(f'Error: {args.model} is not a directory', file = sys.stderr)
  57. sys.exit(1)
  58. # possible tensor data types
  59. # ftype == 0 -> float32
  60. # ftype == 1 -> float16
  61. # map from ftype to string
  62. ftype_str = ["f32", "f16"]
  63. if args.outfile is not None:
  64. fname_out = args.outfile
  65. else:
  66. # output in the same directory as the model by default
  67. fname_out = dir_model / f'ggml-model-{ftype_str[ftype]}.gguf'
  68. print("gguf: loading model "+dir_model.name)
  69. with open(dir_model / "config.json", "r", encoding="utf-8") as f:
  70. hparams = json.load(f)
  71. if hparams["architectures"][0] != "GPTBigCodeForCausalLM":
  72. print("Model architecture not supported: " + hparams["architectures"][0])
  73. sys.exit(1)
  74. # get number of model parts
  75. num_parts = count_model_parts(dir_model)
  76. ARCH=gguf.MODEL_ARCH.STARCODER
  77. gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  78. print("gguf: get model metadata")
  79. block_count = hparams["n_layer"]
  80. gguf_writer.add_name("StarCoder")
  81. gguf_writer.add_context_length(hparams["n_positions"])
  82. gguf_writer.add_embedding_length(hparams["n_embd"])
  83. gguf_writer.add_feed_forward_length(4 * hparams["n_embd"])
  84. gguf_writer.add_block_count(block_count)
  85. gguf_writer.add_head_count(hparams["n_head"])
  86. gguf_writer.add_head_count_kv(1)
  87. gguf_writer.add_layer_norm_eps(hparams["layer_norm_epsilon"])
  88. gguf_writer.add_file_type(ftype)
  89. # TOKENIZATION
  90. print("gguf: get tokenizer metadata")
  91. tokens: list[bytearray] = []
  92. scores: list[float] = []
  93. toktypes: list[int] = []
  94. tokenizer_json_file = dir_model / 'tokenizer.json'
  95. if not tokenizer_json_file.is_file():
  96. print(f'Error: Missing {tokenizer_json_file}', file = sys.stderr)
  97. sys.exit(1)
  98. # gpt2 tokenizer
  99. gguf_writer.add_tokenizer_model("gpt2")
  100. with open(tokenizer_json_file, "r", encoding="utf-8") as f:
  101. tokenizer_json = json.load(f)
  102. print("gguf: get gpt2 tokenizer vocab")
  103. # The number of tokens in tokenizer.json can differ from the expected vocab size.
  104. # This causes downstream issues with mismatched tensor sizes when running the inference
  105. vocab_size = hparams["vocab_size"] if "vocab_size" in hparams else len(tokenizer_json["model"]["vocab"])
  106. # ref: https://github.com/cmp-nct/ggllm.cpp/blob/master/falcon_convert.py
  107. tokenizer = AutoTokenizer.from_pretrained(dir_model)
  108. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
  109. byte_encoder = bytes_to_unicode()
  110. byte_decoder = {v: k for k, v in byte_encoder.items()}
  111. for i in range(vocab_size):
  112. if i in reverse_vocab:
  113. try:
  114. text = bytearray([byte_decoder[c] for c in reverse_vocab[i]])
  115. except KeyError:
  116. text = bytearray()
  117. for c in reverse_vocab[i]:
  118. if ord(c) < 256: # single byte character
  119. text.append(byte_decoder[ord(c)])
  120. else: # multibyte special token character
  121. text.extend(c.encode('utf-8'))
  122. else:
  123. print(f"Key {i} not in tokenizer vocabulary. Padding with an arbitrary token.")
  124. pad_token = f"[PAD{i}]".encode("utf8")
  125. text = bytearray(pad_token)
  126. tokens.append(text)
  127. scores.append(0.0) # dymmy
  128. toktypes.append(gguf.TokenType.NORMAL) # dummy
  129. gguf_writer.add_token_list(tokens)
  130. gguf_writer.add_token_scores(scores)
  131. gguf_writer.add_token_types(toktypes)
  132. special_vocab = gguf.SpecialVocab(dir_model, load_merges = True)
  133. special_vocab.add_to_gguf(gguf_writer)
  134. # TENSORS
  135. tensor_map = gguf.get_tensor_name_map(ARCH,block_count)
  136. # params for qkv transform
  137. n_head = hparams["n_head"]
  138. n_head_kv = hparams["n_head_kv"] if "n_head_kv" in hparams else 1
  139. head_dim = hparams["n_embd"] // n_head
  140. # tensor info
  141. print("gguf: get tensor metadata")
  142. if num_parts == 0:
  143. part_names = iter(("pytorch_model.bin",))
  144. else:
  145. part_names = (
  146. f"pytorch_model-{n:05}-of-{num_parts:05}.bin" for n in range(1, num_parts + 1)
  147. )
  148. for part_name in part_names:
  149. if args.vocab_only:
  150. break
  151. print("gguf: loading model part '" + part_name + "'")
  152. model_part = torch.load(dir_model / part_name, map_location="cpu")
  153. for name in model_part.keys():
  154. data = model_part[name]
  155. old_dtype = data.dtype
  156. # convert any unsupported data types to float32
  157. if data.dtype != torch.float16 and data.dtype != torch.float32:
  158. data = data.to(torch.float32)
  159. data = data.squeeze().numpy()
  160. # map tensor names
  161. new_name = tensor_map.get_name(name, try_suffixes = (".weight", ".bias"))
  162. if new_name is None:
  163. print("Can not map tensor '" + name + "'")
  164. sys.exit()
  165. n_dims = len(data.shape)
  166. data_dtype = data.dtype
  167. # if f32 desired, convert any float16 to float32
  168. if ftype == 0 and data_dtype == np.float16:
  169. data = data.astype(np.float32)
  170. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  171. if ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  172. data = data.astype(np.float32)
  173. # if f16 desired, convert any float32 2-dim weight tensors to float16
  174. if ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  175. data = data.astype(np.float16)
  176. print(name, "=>", new_name + ", shape = " + str(data.shape) + ", " + str(old_dtype) + " --> " + str(data.dtype))
  177. gguf_writer.add_tensor(new_name, data)
  178. print("gguf: write header")
  179. gguf_writer.write_header_to_file()
  180. print("gguf: write metadata")
  181. gguf_writer.write_kv_data_to_file()
  182. if not args.vocab_only:
  183. print("gguf: write tensors")
  184. gguf_writer.write_tensors_to_file()
  185. gguf_writer.close()
  186. print(f"gguf: model successfully exported to '{fname_out}'")
  187. print("")