ggml_convert.py 13 KB

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