ggml_convert.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 math
  8. import struct
  9. from enum import Enum
  10. from io import BufferedWriter
  11. from pathlib import Path
  12. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  13. import torch
  14. from fairseq2.assets import AssetCard
  15. from fairseq2.models.transformer.frontend import TransformerEmbeddingFrontend
  16. from fairseq2.nn import SinusoidalPositionEncoder
  17. from fairseq2.nn.transformer import RelativePositionalEncoding
  18. from seamless_communication.models.unity import load_unity_config, load_unity_model
  19. import ggml
  20. Preprocessor = Callable[[Any], Any]
  21. def convert_model(
  22. model_name: Union[str, torch.nn.Module],
  23. out: Optional[Path] = None,
  24. hparams: Optional[Dict[str, Any]] = None,
  25. ) -> None:
  26. if isinstance(model_name, str):
  27. # Load the corresponding fairseq2 model
  28. if out is None:
  29. out = Path(model_name).with_suffix(".ggml")
  30. # The type of model depends on the name
  31. if "unity" in model_name or "seamlessM4T" in model_name:
  32. if hparams is None:
  33. model_config = load_unity_config(model_name)
  34. hparams = flatten_config(
  35. dataclasses.asdict(model_config), separator="__"
  36. )
  37. print(hparams)
  38. model = load_unity_model(model_name)
  39. else:
  40. raise ValueError(f"Unsupported model type: {model_name}")
  41. else:
  42. # Use the model passed explicitly
  43. assert (
  44. out is not None
  45. ), "output path is required when explicitly passing a module"
  46. hparams = hparams or {}
  47. model = model_name
  48. state_dict = model.state_dict()
  49. fixup_model(model, state_dict)
  50. layer_config = read_layer_config(model)
  51. with out.open("wb") as o:
  52. write_ggml_file(o, hparams, layer_config, state_dict)
  53. def _nested_getattr(model: Any, name: str) -> Any:
  54. parts = name.split(".")
  55. node = model
  56. for part in parts:
  57. node = getattr(node, part)
  58. if node is None:
  59. return None
  60. return node
  61. def find_children(model: torch.nn.Module, t: type) -> List[Tuple[str, torch.nn.Module]]:
  62. queue = list(model._modules.items())
  63. modules = []
  64. while queue:
  65. name, node = queue.pop()
  66. if node is None:
  67. continue
  68. if isinstance(node, t):
  69. modules.append((name, node))
  70. for child_name, child_node in node._modules.items():
  71. queue.append((".".join((name, child_name)), child_node))
  72. return modules
  73. def fixup_model(model: torch.nn.Module, state_dict: Dict[str, torch.Tensor]) -> None:
  74. # Bake the embedding scaling into the weights
  75. frontends = find_children(model, TransformerEmbeddingFrontend)
  76. print(
  77. "Upgrading the following TransformerEmbeddingFrontend:",
  78. [x[0] for x in frontends],
  79. )
  80. for name, frontend in frontends:
  81. embed_weights = state_dict[name + ".embed.weight"]
  82. state_dict[name + ".embed.weight"] = embed_weights * frontend.scale
  83. # Sinusoidal embeddings are typically not saved since they are easily recomputed,
  84. # but this allows to avoid porting the sinusoidal logic to GGML
  85. pos_encoders = find_children(model, SinusoidalPositionEncoder)
  86. print(
  87. "Upgrading the following SinusoidalPositionEncoder:",
  88. [x[0] for x in pos_encoders],
  89. )
  90. for name, pos_encoder in pos_encoders:
  91. assert isinstance(pos_encoder.weight, torch.Tensor)
  92. assert name not in state_dict
  93. state_dict[name] = pos_encoder.weight
  94. relative_pos_encs = find_children(model, RelativePositionalEncoding)
  95. # speech_encoder has several copies of the relative_pos_enc module.
  96. # For efficiency reasons we only make one copy of it to GGML.
  97. if relative_pos_encs:
  98. print("Merging all speech_encoder RelativePositionalEncoding into one.")
  99. _, rel_pos_enc = relative_pos_encs[0]
  100. assert isinstance(rel_pos_enc.weight, torch.Tensor)
  101. state_dict["speech_encoder.pos_enc"] = rel_pos_enc.weight
  102. def write_ggml_file(
  103. out: BufferedWriter,
  104. hparams: Dict[str, Any],
  105. layer_config: Dict[str, Any],
  106. state_dict: Dict[str, torch.Tensor],
  107. ) -> None:
  108. write_ggml_header(out)
  109. write_hparams(out, hparams)
  110. write_hparams(out, layer_config)
  111. write_state_dict(out, state_dict)
  112. def write_ggml_header(out: BufferedWriter) -> None:
  113. """Write GGML header (in reverse cause big-endian)"""
  114. out.write(b"ggml"[::-1])
  115. def write_hparams(out: BufferedWriter, hparams: Dict[str, Any]) -> None:
  116. """Write hyper parameters.
  117. :params hparams:
  118. flattened dict containing model's hyper parameters.
  119. """
  120. simple_vals = {}
  121. for key, value in hparams.items():
  122. try:
  123. simple_vals[key] = to_ctype(value)
  124. except ValueError:
  125. logging.warning(f"Skipping config for key {key}={value!r}")
  126. continue
  127. out.write(struct.pack("<q", len(simple_vals)))
  128. for key, (ctype, cvalue) in simple_vals.items():
  129. write_string(out, key)
  130. b = struct.pack(ctype, cvalue)
  131. assert len(b) == 8
  132. out.write(b)
  133. logging.info(f"Saved {len(simple_vals)} params.")
  134. def write_state_dict(out: BufferedWriter, state_dict: Dict[str, torch.Tensor]) -> None:
  135. """Write pytorch state dict.
  136. :paras state_dict:
  137. state dict returned by pytorch model
  138. """
  139. out.write(struct.pack("<q", len(state_dict)))
  140. # Size of each tensor
  141. byte_size = sum(x.numel() * x.element_size() for x in state_dict.values())
  142. # + tensor overhead
  143. byte_size += ggml.ggml_tensor_overhead() * (len(state_dict) + 10)
  144. out.write(struct.pack("<q", byte_size))
  145. logging.warning(
  146. f"Saving a ggml file with {len(state_dict)} tensors, for an estimated amount of {byte_size / (1024**3):.3f} GGML Gb"
  147. )
  148. for key, value in state_dict.items():
  149. write_string(out, key)
  150. if key.endswith(".bias") and value.ndim == 1 and "adaptor" not in key:
  151. # GGML broadcasting isn't as strong as numpy
  152. value = value.reshape(1, -1)
  153. if "pointwise_conv" in key: # pointwise_conv / depthwise_conv
  154. value = value.squeeze(-1)
  155. if "depthwise_conv" in key:
  156. value = value.squeeze(1)
  157. write_tensor(out, value.contiguous())
  158. def write_string(out: BufferedWriter, value: str) -> None:
  159. """Write string in utf-8 format.
  160. :params value:
  161. string value to dump.
  162. """
  163. str_ = value.encode("utf-8")
  164. packed_len = struct.pack("<i", len(str_))
  165. assert len(packed_len) == 4
  166. out.write(packed_len)
  167. out.write(str_)
  168. def write_tensor(out: BufferedWriter, value: torch.Tensor) -> None:
  169. """Write torch tensor in ggml format.
  170. First we save the number of dimensions and the dtype.
  171. Then we save the data as numpy array.
  172. :params value:
  173. Tensor to dump.
  174. """
  175. if value.dtype is torch.int64:
  176. # GGML doesn't have int64, downcast it
  177. value = value.to(dtype=torch.int32)
  178. if value.ndim == 0:
  179. # GGML doesn't support scalar as tensors.
  180. value = value.reshape(1)
  181. data = value.numpy()
  182. n_dims = data.ndim
  183. assert n_dims < 5, "ggml doesn't support 5 dims tensors"
  184. assert n_dims >= 1, "ggml doesn't support 0 dim tensors"
  185. ftype = torch_to_ggml_type(value.dtype)
  186. out.write(struct.pack("<i", n_dims))
  187. out.write(struct.pack("<i", ftype))
  188. for i in range(n_dims):
  189. # ggml uses long for shape
  190. out.write(struct.pack("<q", data.shape[n_dims - 1 - i]))
  191. data.tofile(out)
  192. def torch_to_ggml_type(dtype: type) -> int:
  193. if dtype is torch.float32:
  194. return ggml.GGML_TYPE_F32
  195. elif dtype is torch.float16:
  196. return ggml.GGML_TYPE_F16
  197. elif dtype is torch.int32:
  198. return ggml.GGML_TYPE_I32
  199. else:
  200. raise NotImplementedError(f"{dtype} is not mapped to a GGML_TYPE")
  201. def flatten_config(
  202. config: Dict[str, Any],
  203. separator: str,
  204. config_preprocessor: Optional[Preprocessor] = None,
  205. ) -> Dict[str, Any]:
  206. """Flatten nested dictionnary
  207. :param config:
  208. nested dictionnary containing model config.
  209. :param separator:
  210. string separator used when flattening nested hparams
  211. :param config_preprocessor:
  212. Preprocessor used for config/hparams values
  213. :returns:
  214. flat dictionnary
  215. """
  216. if config_preprocessor is None:
  217. config_preprocessor = lambda x: x
  218. def __flatten(config: Dict[str, Any], prefix: str = "") -> Dict[str, Any]:
  219. result = {}
  220. for key in config:
  221. new_key = f"{prefix}{key}"
  222. if isinstance(config[key], dict):
  223. nested_result = __flatten(config[key], f"{new_key}{separator}")
  224. result.update(nested_result)
  225. else:
  226. new_config = config_preprocessor(config[key])
  227. if new_config is not None:
  228. result[new_key] = config[key]
  229. return result
  230. return __flatten(config)
  231. def read_layer_config(model: torch.nn.Module) -> Dict[str, Any]:
  232. layer_config = {}
  233. def _append_node_config(node: Any, prefix: str) -> None:
  234. for k, v in node.__dict__.items():
  235. # Skip special members. In particular all children module and tensors
  236. # will be hidden in special dicts `_parameters` and `_modules`
  237. if k.startswith("_"):
  238. continue
  239. # All modules have a "training" flag
  240. if k == "training":
  241. continue
  242. if v is None:
  243. continue
  244. try:
  245. to_ctype(v)
  246. except ValueError:
  247. logging.warning(f"Skipping layer config {k}={v!r}")
  248. continue
  249. layer_config[prefix + k] = v
  250. _append_node_config(model, "")
  251. for name, node in find_children(model, torch.nn.Module):
  252. _append_node_config(node, name + ".")
  253. return layer_config
  254. def to_ctype(value: Any) -> Tuple[str, Any]:
  255. """Transform python type to ctype.
  256. Note: we always use little-endian and 8-byte types.
  257. This make the format independent of the current platform.
  258. :params value:
  259. value to cast into ctype
  260. :returns:
  261. A tuple of ctype and cvalue.
  262. """
  263. if isinstance(value, int):
  264. return ("<q", value)
  265. if isinstance(value, float):
  266. return ("<d", value)
  267. if isinstance(value, bool):
  268. return ("<q", value)
  269. if isinstance(value, Enum):
  270. return ("<q", value.value)
  271. if isinstance(value, tuple) and len(value) == 1:
  272. return to_ctype(value[0])
  273. if isinstance(value, str) and len(value) < 8:
  274. value = bytes(value, "ascii")
  275. if len(value) < 8:
  276. value = value + (8 - len(value)) * b"\0"
  277. return ("8s", value)
  278. raise ValueError(f"Unsupported type {type(value)}")
  279. def get_cpp_type(value: Any) -> str:
  280. """Return equivalent cpp type in string format
  281. :params value:
  282. value to cast into ctype
  283. :returns:
  284. str containing cpp type
  285. """
  286. # used to have compatibility between types
  287. try:
  288. ctype, _ = to_ctype(value)
  289. except ValueError as e:
  290. return f"// Error: {e}"
  291. if ctype == "i":
  292. return "std::int32_t"
  293. if ctype == "l":
  294. return "std::int64_t"
  295. if ctype == "f":
  296. return "float"
  297. if ctype == "d":
  298. return "double"
  299. if ctype == "?":
  300. return "bool"
  301. raise RuntimeError(
  302. f"Should not have reached this part." f"Missing cpp translation for {ctype}"
  303. )
  304. def generate_hparams_struct(
  305. hparams: Dict[str, Any],
  306. struct_name: str,
  307. ) -> str:
  308. """Generate a c++ struct to hold the model hyper-parameters.
  309. :param hparams:
  310. Flattened config of the model.
  311. :param struct_name:
  312. Name of the generated struct.
  313. """
  314. struct = f"struct {struct_name} {{"
  315. fields = [f" {get_cpp_type(value)} {key};" for key, value in hparams.items()]
  316. struct = "\n".join([struct] + fields + ["};\n"])
  317. valid_fields = [
  318. key for key, value in hparams.items() if "Error" not in get_cpp_type(value)
  319. ]
  320. read_struct = f"void read_{struct_name}({struct_name}& out, std::ifstream &fin) {{"
  321. read_fields = [
  322. f" fin.read((char*) &out.{field}, sizeof(out.{field}));"
  323. for field in valid_fields
  324. ]
  325. read_struct = "\n".join([read_struct] + read_fields + ["};\n"])
  326. return "\n".join([struct, read_struct])
  327. if __name__ == "__main__":
  328. import func_argparse
  329. func_argparse.single_main(convert_model)