ggml_convert.py 14 KB

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