ggml_convert.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 torch
  13. from fairseq2.assets import AssetCard
  14. from seamless_communication.models.unity import load_unity_config, load_unity_model
  15. Preprocessor = Callable[[Any], Any]
  16. def to_ctype(value: Any) -> Tuple[str, Any]:
  17. """Transform python type to ctype.
  18. :params value:
  19. value to cast into ctype
  20. :returns:
  21. A tuple of ctype and cvalue.
  22. """
  23. if isinstance(value, int):
  24. return ("i", value)
  25. if isinstance(value, float):
  26. return ("f", value)
  27. if isinstance(value, bool):
  28. return ("?", value)
  29. if isinstance(value, Enum):
  30. return ("i", value.value)
  31. raise ValueError(f"Unsupported type {type(value)}")
  32. def get_cpp_type(value: Any) -> str:
  33. """Return equivalent cpp type in string format
  34. :params value:
  35. value to cast into ctype
  36. :returns:
  37. str containing cpp type
  38. """
  39. # used to have compatibility between types
  40. try:
  41. ctype, _ = to_ctype(value)
  42. except ValueError as e:
  43. return f"// Error: {e}"
  44. if ctype == "i":
  45. return "std::int32_t"
  46. if ctype == "f":
  47. return "std::float32"
  48. if ctype == "?":
  49. return "bool"
  50. raise RuntimeError(
  51. f"Should not have reached this part." f"Missing cpp translation for {ctype}"
  52. )
  53. def write_ggml_header(out: BufferedWriter) -> None:
  54. """Write GGML header"""
  55. out.write(b"ggml")
  56. def write_hparams(out: BufferedWriter, hparams: Dict[str, Any]) -> None:
  57. """Write hyper parameters.
  58. :params hparams:
  59. flattened dict containing model's hyper parameters.
  60. """
  61. for key, value in hparams.items():
  62. try:
  63. # TODO: this is not cross platform, what's the standard way of writing hparams in GGML ?
  64. ctype, cvalue = to_ctype(value)
  65. out.write(struct.pack(ctype, cvalue))
  66. except ValueError as e:
  67. logging.warning(f"[Warning] {e}. Skipping config for key {key}")
  68. continue
  69. def write_state_dict(out: BufferedWriter, state_dict: Dict[str, torch.Tensor]) -> None:
  70. """Write pytorch state dict.
  71. :paras state_dict:
  72. state dict returned by pytorch model
  73. """
  74. for key, value in state_dict.items():
  75. write_string(out, key)
  76. write_tensor(out, value)
  77. def write_string(out: BufferedWriter, value: str) -> None:
  78. """Write string in utf-8 format.
  79. :params value:
  80. string value to dump.
  81. """
  82. str_ = value.encode("utf-8")
  83. out.write(struct.pack("i", len(str_)))
  84. out.write(str_)
  85. def write_tensor(out: BufferedWriter, value: torch.Tensor) -> None:
  86. """Write torch tensor in ggml format.
  87. First we save the number of dimensions and the dtype.
  88. Then we save the data as numpy array.
  89. :params value:
  90. Tensor to dump.
  91. """
  92. data = value.squeeze().numpy()
  93. n_dims = len(data.shape)
  94. # TODO: Convert to fp16 when necessary!
  95. ftype = 0
  96. out.write(struct.pack("ii", n_dims, ftype))
  97. for i in range(n_dims):
  98. out.write(struct.pack("i", data.shape[n_dims - 1 - i]))
  99. data.tofile(out)
  100. def write_ggml_file(
  101. out: BufferedWriter, hparams: Dict[str, Any], state_dict: Dict[str, torch.Tensor]
  102. ) -> None:
  103. write_ggml_header(out)
  104. write_hparams(out, hparams)
  105. write_state_dict(out, state_dict)
  106. def flatten_config(
  107. config: Dict[str, Any],
  108. separator: str,
  109. config_preprocessor: Optional[Preprocessor] = None,
  110. ) -> Dict[str, Any]:
  111. """Flatten nested dictionnary
  112. :param config:
  113. nested dictionnary containing model config.
  114. :param separator:
  115. string separator used when flattening nested hparams
  116. :param config_preprocessor:
  117. Preprocessor used for config/hparams values
  118. :returns:
  119. flat dictionnary
  120. """
  121. if config_preprocessor is None:
  122. config_preprocessor = lambda x: x
  123. def __flatten(config: Dict[str, Any], prefix: str = "") -> Dict[str, Any]:
  124. result = {}
  125. for key in config:
  126. new_key = f"{prefix}{key}"
  127. if isinstance(config[key], dict):
  128. nested_result = __flatten(config[key], f"{new_key}{separator}")
  129. result.update(nested_result)
  130. else:
  131. new_config = config_preprocessor(config[key])
  132. if new_config is not None:
  133. result[new_key] = config[key]
  134. return result
  135. return __flatten(config)
  136. def generate_hparams_struct(
  137. hparams: Dict[str, Any],
  138. struct_name: str,
  139. ) -> str:
  140. """Generate a c++ struct to hold the model hyper-parameters.
  141. :param hparams:
  142. Flattened config of the model.
  143. :param struct_name:
  144. Name of the generated struct.
  145. """
  146. struct = f"struct {struct_name} {{\n"
  147. fields = "\n".join(
  148. [f" {get_cpp_type(value)} {key};" for key, value in hparams.items()]
  149. )
  150. return struct + fields + "\n};\n"
  151. def main(model_name: str, out: Optional[Path] = None) -> None:
  152. if out is None:
  153. out = Path(model_name).with_suffix(".ggml")
  154. # The type of model depends on the name
  155. if "unity" in model_name or "seamlessM4T" in model_name:
  156. model_config = load_unity_config(model_name)
  157. hparams = flatten_config(dataclasses.asdict(model_config), separator="__")
  158. model = load_unity_model(model_name)
  159. else:
  160. raise ValueError(f"Unsupported model type: {model_name}")
  161. with out.open("wb") as o:
  162. write_ggml_file(o, hparams, model.state_dict())
  163. with out.with_suffix(".hparams.h").open("w") as h:
  164. h.write(generate_hparams_struct(hparams, model_name + "_hparams"))
  165. if __name__ == "__main__":
  166. import func_argparse
  167. func_argparse.single_main(main)