ggml_convert.py 13 KB

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