ggml_convert.py 15 KB

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