ggml_convert.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import dataclasses
  6. import logging
  7. import struct
  8. from enum import Enum
  9. from io import BufferedWriter
  10. from pathlib import Path
  11. from typing import Any, Callable, Dict, Optional, Tuple, Union
  12. import torch
  13. import ggml
  14. from typing import List
  15. from fairseq2.assets import AssetCard
  16. from fairseq2.models.transformer.frontend import TransformerEmbeddingFrontend
  17. from fairseq2.nn import SinusoidalPositionEncoder
  18. from seamless_communication.models.unity import load_unity_config, load_unity_model
  19. Preprocessor = Callable[[Any], Any]
  20. def convert_model(model_name: str, out: Optional[Path] = None) -> None:
  21. if out is None:
  22. out = Path(model_name).with_suffix(".ggml")
  23. # The type of model depends on the name
  24. if "unity" in model_name or "seamlessM4T" in model_name:
  25. model_config = load_unity_config(model_name)
  26. hparams = flatten_config(dataclasses.asdict(model_config), separator="__")
  27. print(hparams)
  28. model = load_unity_model(model_name)
  29. else:
  30. raise ValueError(f"Unsupported model type: {model_name}")
  31. state_dict = model.state_dict()
  32. fixup_model(model, state_dict)
  33. with out.open("wb") as o:
  34. write_ggml_file(o, hparams, state_dict)
  35. with out.with_suffix(".hparams.h").open("w") as h:
  36. h.write(generate_hparams_struct(hparams, "unity_hparams"))
  37. def _nested_getattr(model: Any, name: str) -> Any:
  38. parts = name.split(".")
  39. node = model
  40. for part in parts:
  41. node = getattr(node, part)
  42. if node is None:
  43. return None
  44. return node
  45. def find_children(model: torch.nn.Module, t: type) -> List[Tuple[str, torch.nn.Module]]:
  46. queue = list(model._modules.items())
  47. modules = []
  48. while queue:
  49. name, node = queue.pop()
  50. if node is None:
  51. continue
  52. if isinstance(node, t):
  53. modules.append((name, node))
  54. for child_name, child_node in node._modules.items():
  55. queue.append((".".join((name, child_name)), child_node))
  56. return modules
  57. def fixup_model(model: torch.nn.Module, state_dict: Dict[str, torch.Tensor]) -> None:
  58. # Bake the embedding scaling into the weights
  59. frontends = find_children(model, TransformerEmbeddingFrontend)
  60. print("Upgrading the following TransformerEmbeddingFrontend:", [x[0] for x in frontends])
  61. for name, frontend in frontends:
  62. embed_weights = state_dict[name + ".embed.weight"]
  63. state_dict[name + ".embed.weight"] = embed_weights * frontend.scale
  64. # Sinusoidal embeddings are typically not saved since they are easily recomputed,
  65. # but this allows to avoid porting the sinusoidal logic to GGML
  66. pos_encoders = find_children(model, SinusoidalPositionEncoder)
  67. print("Upgrading the following SinusoidalPositionEncoder:", [x[0] for x in pos_encoders])
  68. for name, pos_encoder in pos_encoders:
  69. assert isinstance(pos_encoder.weight, torch.Tensor)
  70. assert name not in state_dict
  71. state_dict[name] = pos_encoder.weight
  72. def write_ggml_file(
  73. out: BufferedWriter, hparams: Dict[str, Any], state_dict: Dict[str, torch.Tensor]
  74. ) -> None:
  75. write_ggml_header(out)
  76. # Apppend the byte size to the hparams.
  77. if "model_byte_size" not in hparams:
  78. # Size of each tensor
  79. byte_size = sum(x.numel() * x.element_size() for x in state_dict.values())
  80. # + tensor overhead
  81. byte_size += ggml.ggml_tensor_overhead() * (len(state_dict) + 10)
  82. hparams["model_byte_size"] = byte_size
  83. logging.warning(
  84. f"Saving a ggml file with {len(state_dict)} tensors, for an estimated amount of {byte_size / (1024**3)} GGML Gb"
  85. )
  86. # 6877961321223123048
  87. hparams["__end_of_hparams__"] = struct.unpack("l", b"hparams_")[0]
  88. write_hparams(out, hparams)
  89. write_state_dict(out, state_dict)
  90. def write_ggml_header(out: BufferedWriter) -> None:
  91. """Write GGML header (in reverse cause why not)"""
  92. out.write(b"ggml"[::-1])
  93. def write_hparams(out: BufferedWriter, hparams: Dict[str, Any]) -> None:
  94. """Write hyper parameters.
  95. :params hparams:
  96. flattened dict containing model's hyper parameters.
  97. """
  98. # TODO: should we preprend the size of the hparams struct ?
  99. # this would help catch out of sync writer/loader code
  100. for key, value in hparams.items():
  101. try:
  102. # TODO: this is not cross platform, what's the standard way of writing hparams in GGML ?
  103. ctype, cvalue = to_ctype(value)
  104. out.write(struct.pack(ctype, cvalue))
  105. except ValueError as e:
  106. logging.warning(f"[Warning] {e}. Skipping config for key {key}")
  107. continue
  108. def write_state_dict(out: BufferedWriter, state_dict: Dict[str, torch.Tensor]) -> None:
  109. """Write pytorch state dict.
  110. :paras state_dict:
  111. state dict returned by pytorch model
  112. """
  113. for key, value in state_dict.items():
  114. write_string(out, key)
  115. if key.endswith(".bias") and value.ndim == 1:
  116. # GGML broadcasting isn't as strong as numpy
  117. value = value.reshape(1, -1)
  118. write_tensor(out, value.contiguous())
  119. def write_string(out: BufferedWriter, value: str) -> None:
  120. """Write string in utf-8 format.
  121. :params value:
  122. string value to dump.
  123. """
  124. str_ = value.encode("utf-8")
  125. out.write(struct.pack("i", len(str_)))
  126. out.write(str_)
  127. def write_tensor(out: BufferedWriter, value: torch.Tensor) -> None:
  128. """Write torch tensor in ggml format.
  129. First we save the number of dimensions and the dtype.
  130. Then we save the data as numpy array.
  131. :params value:
  132. Tensor to dump.
  133. """
  134. if value.dtype is torch.int64:
  135. # GGML doesn't ahve int64, downcast it
  136. value = value.to(dtype=torch.int32)
  137. if value.ndim == 0:
  138. # GGML doesn't support scalar as tensors.
  139. value = value.reshape(1)
  140. data = value.numpy()
  141. n_dims = data.ndim
  142. assert n_dims < 5, "ggml doesn't support 5 dims tensors"
  143. assert n_dims >= 1, "ggml doesn't support 0 dim tensors"
  144. ftype = torch_to_ggml_type(value.dtype)
  145. out.write(struct.pack("i", n_dims))
  146. out.write(struct.pack("i", ftype))
  147. for i in range(n_dims):
  148. # ggml uses long for shape
  149. out.write(struct.pack("l", data.shape[n_dims - 1 - i]))
  150. data.tofile(out)
  151. def torch_to_ggml_type(dtype: type) -> int:
  152. if dtype is torch.float32:
  153. return ggml.GGML_TYPE_F32
  154. elif dtype is torch.float16:
  155. return ggml.GGML_TYPE_F16
  156. elif dtype is torch.int32:
  157. return ggml.GGML_TYPE_I32
  158. else:
  159. raise NotImplementedError(f"{dtype} is not mapped to a GGML_TYPE")
  160. def flatten_config(
  161. config: Dict[str, Any],
  162. separator: str,
  163. config_preprocessor: Optional[Preprocessor] = None,
  164. ) -> Dict[str, Any]:
  165. """Flatten nested dictionnary
  166. :param config:
  167. nested dictionnary containing model config.
  168. :param separator:
  169. string separator used when flattening nested hparams
  170. :param config_preprocessor:
  171. Preprocessor used for config/hparams values
  172. :returns:
  173. flat dictionnary
  174. """
  175. if config_preprocessor is None:
  176. config_preprocessor = lambda x: x
  177. def __flatten(config: Dict[str, Any], prefix: str = "") -> Dict[str, Any]:
  178. result = {}
  179. for key in config:
  180. new_key = f"{prefix}{key}"
  181. if isinstance(config[key], dict):
  182. nested_result = __flatten(config[key], f"{new_key}{separator}")
  183. result.update(nested_result)
  184. else:
  185. new_config = config_preprocessor(config[key])
  186. if new_config is not None:
  187. result[new_key] = config[key]
  188. return result
  189. return __flatten(config)
  190. def to_ctype(value: Any) -> Tuple[str, Any]:
  191. """Transform python type to ctype.
  192. :params value:
  193. value to cast into ctype
  194. :returns:
  195. A tuple of ctype and cvalue.
  196. """
  197. if isinstance(value, int):
  198. return ("l", value)
  199. if isinstance(value, float):
  200. return ("f", value)
  201. if isinstance(value, bool):
  202. return ("?", value)
  203. if isinstance(value, Enum):
  204. return ("i", value.value)
  205. raise ValueError(f"Unsupported type {type(value)}")
  206. def get_cpp_type(value: Any) -> str:
  207. """Return equivalent cpp type in string format
  208. :params value:
  209. value to cast into ctype
  210. :returns:
  211. str containing cpp type
  212. """
  213. # used to have compatibility between types
  214. try:
  215. ctype, _ = to_ctype(value)
  216. except ValueError as e:
  217. return f"// Error: {e}"
  218. if ctype == "i":
  219. return "std::int32_t"
  220. if ctype == "l":
  221. return "std::int64_t"
  222. if ctype == "f":
  223. return "float"
  224. if ctype == "?":
  225. return "bool"
  226. raise RuntimeError(
  227. f"Should not have reached this part." f"Missing cpp translation for {ctype}"
  228. )
  229. def generate_hparams_struct(
  230. hparams: Dict[str, Any],
  231. struct_name: str,
  232. ) -> str:
  233. """Generate a c++ struct to hold the model hyper-parameters.
  234. :param hparams:
  235. Flattened config of the model.
  236. :param struct_name:
  237. Name of the generated struct.
  238. """
  239. struct = f"struct {struct_name} {{"
  240. fields = [f" {get_cpp_type(value)} {key};" for key, value in hparams.items()]
  241. struct = "\n".join([struct] + fields + ["};\n"])
  242. valid_fields = [
  243. key for key, value in hparams.items() if "Error" not in get_cpp_type(value)
  244. ]
  245. read_struct = f"void read_{struct_name}({struct_name}& out, std::ifstream &fin) {{"
  246. read_fields = [
  247. f" fin.read((char*) &out.{field}, sizeof(out.{field}));"
  248. for field in valid_fields
  249. ]
  250. read_struct = "\n".join([read_struct] + read_fields + ["};\n"])
  251. return "\n".join([struct, read_struct])
  252. if __name__ == "__main__":
  253. import func_argparse
  254. func_argparse.single_main(convert_model)