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