ggml_convert.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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, Set, final
  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. from fairseq2.data.text import SentencePieceTokenizerBase
  20. from fairseq2.data.typing import PathLike
  21. from typing import Sequence
  22. from fairseq2.data.text import SentencePieceEncoder, SentencePieceTokenizerBase
  23. from fairseq2.typing import Device, finaloverride
  24. from fairseq2.models.utils import TokenizerLoaderBase
  25. from fairseq2.assets import asset_store, download_manager
  26. from seamless_communication.models.unity.builder import UnitYConfig, create_unity_model
  27. from fairseq2.models.utils import ModelLoader
  28. from seamless_communication.models.unity.model import UnitYModel
  29. import ggml
  30. import re
  31. Preprocessor = Callable[[Any], Any]
  32. log = logging.getLogger("ggml_convert")
  33. SMALLER_MODELS = [
  34. "unity_nano",
  35. "unity_micro",
  36. ] # Trained with fairseq2, with custom dict (not original NLLB ones)
  37. @final
  38. class NllbLikeTokenizer(SentencePieceTokenizerBase):
  39. """The only difference between this class and NllbTokenizer is it doesn't add a <pad> to control symbol list.
  40. Since NllbTokenizer is defined as final, we couldn't inherit from it directly. So copying ~everything"""
  41. langs: Set[str]
  42. default_lang: str
  43. def __init__(
  44. self, pathname: PathLike, langs: Sequence[str], default_lang: str
  45. ) -> None:
  46. """
  47. :param pathname:
  48. The pathname of the SentencePiece model file.
  49. :param langs:
  50. The list of supported languages.
  51. :param default_lang:
  52. The fall-back language if no language is specified.
  53. """
  54. # Each language is represented by a `__lang__` control symbol.
  55. control_symbols = [f"__{lang}__" for lang in langs]
  56. # Internal control symbols that are not relevant for eval use.
  57. control_symbols.extend(["<MINED_DATA>", "<MMT_BT_DATA>", "<SMT_BT_DATA>"])
  58. super().__init__(pathname, control_symbols)
  59. self.langs = set(langs)
  60. self.default_lang = default_lang
  61. @finaloverride
  62. def create_encoder(
  63. self,
  64. *,
  65. task: Optional[str] = None,
  66. lang: Optional[str] = None,
  67. mode: Optional[str] = None,
  68. device: Optional[Device] = None,
  69. pin_memory: bool = False,
  70. ) -> SentencePieceEncoder:
  71. """Create a token encoder.
  72. :param task:
  73. Must be 'translation'. If ``None``, defaults to 'translation'.
  74. :param lang:
  75. A language from :attr:`langs`. If ``None``, defaults to
  76. :attr:`default_lang`.
  77. :param mode:
  78. Must be 'source' or 'target'. Set to 'source' if ``lang`` is the
  79. source language; set to 'target' if ``lang`` is the target language.
  80. If ``None``, defaults to 'source'.
  81. :param device:
  82. The device on which to construct tensors.
  83. :param pin_memory:
  84. If ``True``, uses pinned memory while constructing tensors.
  85. """
  86. if task is not None and task != "translation":
  87. raise ValueError(f"`task` must be 'translation', but is '{task}' instead.")
  88. if lang is None:
  89. lang = self.default_lang
  90. if lang not in self.langs:
  91. raise ValueError(
  92. f"`lang` must be a supported language, but is '{lang}' instead."
  93. )
  94. if mode is None or mode == "source":
  95. # NLLB models expect a language token in place of BOS in source
  96. # sequences.
  97. prefix_tokens = [f"__{lang}__"]
  98. suffix_tokens = ["</s>"]
  99. elif mode == "source_mining":
  100. prefix_tokens = [f"__{lang}__", "<MINED_DATA>"]
  101. suffix_tokens = ["</s>"]
  102. elif mode == "source_mmt_bt":
  103. prefix_tokens = [f"__{lang}__", "<MMT_BT_DATA>"]
  104. suffix_tokens = ["</s>"]
  105. elif mode == "source_smt_bt":
  106. prefix_tokens = [f"__{lang}__", "<SMT_BT_DATA>"]
  107. suffix_tokens = ["</s>"]
  108. elif mode == "target":
  109. # Target sequences are expected to start with an EOS, followed by
  110. # the language token.
  111. prefix_tokens = ["</s>", f"__{lang}__"]
  112. suffix_tokens = []
  113. else:
  114. raise ValueError(
  115. f"`mode` must be 'source' or 'target', but is '{mode}' instead."
  116. )
  117. return SentencePieceEncoder(
  118. self.model,
  119. prefix_tokens=prefix_tokens,
  120. suffix_tokens=suffix_tokens,
  121. device=device,
  122. pin_memory=pin_memory,
  123. )
  124. load_unity_model_without_conversion = ModelLoader[UnitYModel, UnitYConfig](
  125. asset_store,
  126. download_manager,
  127. unity.load_unity_config,
  128. create_unity_model,
  129. None,
  130. restrict_checkpoints=False,
  131. )
  132. @final
  133. class NllbLikeTokenizerLoader(TokenizerLoaderBase[NllbLikeTokenizer]):
  134. """Loads tokenizers used by NLLB models."""
  135. @finaloverride
  136. def _load(self, pathname: Path, card: AssetCard) -> NllbLikeTokenizer:
  137. langs = card.field("langs").as_list(str)
  138. default_lang = card.field("default_lang").as_(str)
  139. return NllbLikeTokenizer(pathname, langs, default_lang)
  140. def convert_model(
  141. model_name: Union[str, torch.nn.Module],
  142. out: Optional[Path] = None,
  143. layers: str = "",
  144. hparams: Optional[Dict[str, Any]] = None,
  145. vocab: Optional[List[Tuple[str, float]]] = None,
  146. fp16: bool = False,
  147. ) -> None:
  148. if isinstance(model_name, str):
  149. # Load the corresponding fairseq2 model
  150. if out is None:
  151. out = Path(model_name).with_suffix(".ggml")
  152. # The type of model depends on the name
  153. if "unity" in model_name or "seamlessM4T" in model_name:
  154. if hparams is None:
  155. model_config = unity.load_unity_config(model_name)
  156. hparams = flatten_config(
  157. dataclasses.asdict(model_config), separator="__"
  158. )
  159. log.info(hparams)
  160. # Need the diverge here because current default in SC is to convert from fairseq1 ckpt format
  161. if model_name in SMALLER_MODELS:
  162. model = load_unity_model_without_conversion(model_name)
  163. else:
  164. model = unity.load_unity_model(model_name)
  165. if vocab is None:
  166. # Need the diverge here because current default in SC is to add a separate <pad>
  167. # as control symbol in NllbTokenizer
  168. if model_name in SMALLER_MODELS:
  169. tokenizer = NllbLikeTokenizerLoader(asset_store, download_manager)(
  170. model_name
  171. )
  172. else:
  173. tokenizer = unity.load_unity_text_tokenizer(model_name)
  174. vocab = read_vocab(tokenizer)
  175. else:
  176. raise ValueError(f"Unsupported model type: {model_name}")
  177. else:
  178. # Use the model passed explicitly
  179. assert (
  180. out is not None
  181. ), "output path is required when explicitly passing a module"
  182. hparams = hparams or {}
  183. model = model_name
  184. state_dict = model.state_dict()
  185. if layers:
  186. state_dict = {k: v for k, v in state_dict.items() if re.match(layers, k)}
  187. fixup_model(model, state_dict, layer_filter=layers)
  188. layer_config = read_layer_config(model, layer_filter=layers)
  189. vocab = vocab or []
  190. write_ggml_file(out, hparams, layer_config, vocab, state_dict, fp16)
  191. def _nested_getattr(model: Any, name: str) -> Any:
  192. parts = name.split(".")
  193. node = model
  194. for part in parts:
  195. node = getattr(node, part)
  196. if node is None:
  197. return None
  198. return node
  199. def find_children(model: torch.nn.Module, t: type, layer_filter: str = "") -> List[Tuple[str, torch.nn.Module]]:
  200. queue = list(model._modules.items())
  201. modules = []
  202. while queue:
  203. name, node = queue.pop()
  204. if node is None:
  205. continue
  206. if layer_filter and not re.match(layer_filter, name):
  207. continue
  208. if isinstance(node, t):
  209. modules.append((name, node))
  210. for child_name, child_node in node._modules.items():
  211. queue.append((".".join((name, child_name)), child_node))
  212. return modules
  213. def fixup_model(model: torch.nn.Module, state_dict: Dict[str, torch.Tensor], layer_filter: str) -> None:
  214. # Bake the embedding scaling into the weights
  215. frontends = find_children(model, TransformerEmbeddingFrontend, layer_filter)
  216. if frontends:
  217. log.info(
  218. "Upgrading the following TransformerEmbeddingFrontend: {}",
  219. [x[0] for x in frontends],
  220. )
  221. for name, frontend in frontends:
  222. embed_weights = state_dict[name + ".embed.weight"]
  223. state_dict[name + ".embed.weight"] = embed_weights * frontend.scale
  224. # Sinusoidal embeddings are typically not saved since they are easily recomputed,
  225. # but this allows to avoid porting the sinusoidal logic to GGML
  226. pos_encoders = find_children(model, SinusoidalPositionEncoder, layer_filter)
  227. if pos_encoders:
  228. log.info(
  229. "Upgrading the following SinusoidalPositionEncoder: {}",
  230. [x[0] for x in pos_encoders],
  231. )
  232. for name, pos_encoder in pos_encoders:
  233. assert isinstance(pos_encoder.freqs, torch.Tensor)
  234. assert name not in state_dict
  235. state_dict[name] = pos_encoder.freqs
  236. relative_pos_encs = find_children(model, RelativePositionalEncoding, layer_filter)
  237. # speech_encoder has several copies of the relative_pos_enc module.
  238. # For efficiency reasons we only make one copy of it to GGML.
  239. if relative_pos_encs:
  240. log.info("Merging all speech_encoder RelativePositionalEncoding into one.")
  241. _, rel_pos_enc = relative_pos_encs[0]
  242. assert isinstance(rel_pos_enc.freqs, torch.Tensor)
  243. state_dict["speech_encoder.pos_enc"] = rel_pos_enc.freqs
  244. def read_vocab(tokenizer: Any) -> List[Tuple[str, float]]:
  245. vocab_info = tokenizer.vocab_info
  246. vocab = [
  247. (tokenizer.model.index_to_token(i).replace("▁", " "), -i)
  248. for i in range(vocab_info.size)
  249. ]
  250. return vocab # type: ignore[return-value]
  251. def write_ggml_file(
  252. out: Path,
  253. hparams: Dict[str, Any],
  254. layer_config: Dict[str, Any],
  255. vocab: List[Tuple[str, float]],
  256. state_dict: Dict[str, torch.Tensor],
  257. fp16: bool,
  258. ) -> None:
  259. with out.open("wb") as o:
  260. write_ggml_header(o)
  261. write_hparams(o, hparams)
  262. write_hparams(o, layer_config)
  263. write_vocab(o, vocab)
  264. write_state_dict(o, state_dict, fp16)
  265. def write_ggml_header(out: BufferedWriter) -> None:
  266. """Write GGML header (in reverse cause big-endian)"""
  267. out.write(b"ggml"[::-1])
  268. def write_hparams(out: BufferedWriter, hparams: Dict[str, Any]) -> None:
  269. """Write hyper parameters.
  270. :params hparams:
  271. flattened dict containing model's hyper parameters.
  272. """
  273. simple_vals = {}
  274. for key, value in hparams.items():
  275. try:
  276. simple_vals[key] = to_ctype(value)
  277. except ValueError:
  278. logging.warning(f"Skipping config for key {key}={value!r}")
  279. continue
  280. out.write(struct.pack("<q", len(simple_vals)))
  281. for key, (ctype, cvalue) in simple_vals.items():
  282. write_string(out, key)
  283. b = struct.pack(ctype, cvalue)
  284. assert len(b) == 8
  285. out.write(b)
  286. logging.info(f"Saved {len(simple_vals)} params.")
  287. def write_vocab(out: BufferedWriter, vocab: List[Tuple[str, float]]) -> None:
  288. out.write(struct.pack("<q", len(vocab)))
  289. # Write all words concatenated in a buffer
  290. words = [bytes(w, "utf8") for w, score in vocab]
  291. packed_words = b"\0".join(words)
  292. # We use i32 to allow reusing the string loading codes
  293. packed_len = struct.pack("<i", len(packed_words))
  294. out.write(packed_len)
  295. out.write(packed_words)
  296. lengths = torch.tensor([len(w) for w in words], dtype=torch.int8)
  297. write_tensor(out, lengths)
  298. scores = torch.tensor([score for w, score in vocab], dtype=torch.float32)
  299. write_tensor(out, scores)
  300. def write_state_dict(
  301. out: BufferedWriter, state_dict: Dict[str, torch.Tensor], fp16: bool
  302. ) -> None:
  303. """Write pytorch state dict.
  304. :params state_dict:
  305. state dict returned by pytorch model
  306. :params fp16:
  307. convert float32 tensors to float16 on disk
  308. """
  309. out.write(struct.pack("<q", len(state_dict)))
  310. # True size of each tensor (before downcasting to float16)
  311. true_byte_size = sum(x.numel() * x.element_size() for x in state_dict.values())
  312. out.write(struct.pack("<q", true_byte_size))
  313. GB = 1024**3
  314. if not fp16:
  315. log.warning(
  316. f"Saving a ggml file with {len(state_dict)} tensors, totalling {true_byte_size / GB:.3f}Gb"
  317. )
  318. else:
  319. def _fp16_byte_size(x: torch.Tensor) -> int:
  320. full_byte_size = x.numel() * x.element_size()
  321. if fp16 and x.dtype == torch.float32:
  322. full_byte_size //= 2
  323. return full_byte_size
  324. # Compressed size
  325. compressed_byte_size = sum(_fp16_byte_size(x) for x in state_dict.values())
  326. log.warning(
  327. f"Saving a ggml file with {len(state_dict)} tensors, totalling {true_byte_size / GB:.3f}Gb compressed to {compressed_byte_size / GB:.3f}"
  328. )
  329. for key, value in state_dict.items():
  330. write_string(out, key)
  331. if key.endswith(".bias") and value.ndim == 1 and "adaptor" not in key:
  332. # GGML broadcasting isn't as strong as numpy
  333. value = value.reshape(1, -1)
  334. if "pointwise_conv" in key: # pointwise_conv / depthwise_conv
  335. value = value.squeeze(-1)
  336. if "depthwise_conv" in key:
  337. value = value.squeeze(1)
  338. if fp16 and value.dtype == torch.float32:
  339. value = value.to(torch.float16)
  340. write_tensor(out, value.contiguous())
  341. def write_string(out: BufferedWriter, value: str) -> None:
  342. """Write string in utf-8 format.
  343. :params value:
  344. string value to dump.
  345. """
  346. str_ = value.encode("utf-8")
  347. packed_len = struct.pack("<i", len(str_))
  348. assert len(packed_len) == 4
  349. out.write(packed_len)
  350. out.write(str_)
  351. def write_tensor(out: BufferedWriter, value: torch.Tensor) -> None:
  352. """Write torch tensor in ggml format.
  353. First we save the number of dimensions and the dtype.
  354. Then we save the data as numpy array.
  355. :params value:
  356. Tensor to dump.
  357. """
  358. if value.dtype is torch.int64:
  359. # GGML doesn't have int64, downcast it
  360. value = value.to(dtype=torch.int32)
  361. if value.ndim == 0:
  362. # GGML doesn't support scalar as tensors.
  363. value = value.reshape(1)
  364. data = value.numpy()
  365. n_dims = data.ndim
  366. assert n_dims < 5, "ggml doesn't support 5 dims tensors"
  367. assert n_dims >= 1, "ggml doesn't support 0 dim tensors"
  368. ftype = torch_to_ggml_type(value.dtype)
  369. out.write(struct.pack("<i", n_dims))
  370. out.write(struct.pack("<i", ftype))
  371. for i in range(n_dims):
  372. # ggml uses long for shape
  373. out.write(struct.pack("<q", data.shape[n_dims - 1 - i]))
  374. data.tofile(out)
  375. def torch_to_ggml_type(dtype: torch.dtype) -> int:
  376. if dtype is torch.float32:
  377. return ggml.GGML_TYPE_F32
  378. elif dtype is torch.float16:
  379. return ggml.GGML_TYPE_F16
  380. elif dtype is torch.int32:
  381. return ggml.GGML_TYPE_I32
  382. elif dtype is torch.int8:
  383. return ggml.GGML_TYPE_I8
  384. else:
  385. raise NotImplementedError(f"{dtype} is not mapped to a GGML_TYPE")
  386. def flatten_config(
  387. config: Dict[str, Any],
  388. separator: str,
  389. config_preprocessor: Optional[Preprocessor] = None,
  390. ) -> Dict[str, Any]:
  391. """Flatten nested dictionnary
  392. :param config:
  393. nested dictionnary containing model config.
  394. :param separator:
  395. string separator used when flattening nested hparams
  396. :param config_preprocessor:
  397. Preprocessor used for config/hparams values
  398. :returns:
  399. flat dictionnary
  400. """
  401. if config_preprocessor is None:
  402. config_preprocessor = lambda x: x
  403. def __flatten(config: Dict[str, Any], prefix: str = "") -> Dict[str, Any]:
  404. result = {}
  405. for key in config:
  406. new_key = f"{prefix}{key}"
  407. if isinstance(config[key], dict):
  408. nested_result = __flatten(config[key], f"{new_key}{separator}")
  409. result.update(nested_result)
  410. else:
  411. new_config = config_preprocessor(config[key])
  412. if new_config is not None:
  413. result[new_key] = config[key]
  414. return result
  415. return __flatten(config)
  416. def read_layer_config(model: torch.nn.Module, layer_filter: str) -> Dict[str, Any]:
  417. layer_config = {}
  418. def _append_node_config(node: Any, prefix: str) -> None:
  419. for k, v in node.__dict__.items():
  420. # Skip special members. In particular all children module and tensors
  421. # will be hidden in special dicts `_parameters` and `_modules`
  422. if k.startswith("_"):
  423. continue
  424. # All modules have a "training" flag
  425. if k in ("training", "init_fn"):
  426. continue
  427. if v is None:
  428. continue
  429. try:
  430. to_ctype(v)
  431. except ValueError:
  432. log.warning(f"Skipping layer config {k}={v!r}")
  433. continue
  434. layer_config[prefix + k] = v
  435. _append_node_config(model, "")
  436. for name, node in find_children(model, torch.nn.Module, layer_filter):
  437. _append_node_config(node, name + ".")
  438. return layer_config
  439. def to_ctype(value: Any) -> Tuple[str, Any]:
  440. """Transform python type to ctype.
  441. Note: we always use little-endian and 8-byte types.
  442. This make the format independent of the current platform.
  443. :params value:
  444. value to cast into ctype
  445. :returns:
  446. A tuple of ctype and cvalue.
  447. """
  448. if isinstance(value, int):
  449. return ("<q", value)
  450. if isinstance(value, float):
  451. return ("<d", value)
  452. if isinstance(value, bool):
  453. return ("<q", value)
  454. if isinstance(value, Enum):
  455. return ("<q", value.value)
  456. if isinstance(value, tuple) and len(value) == 1:
  457. return to_ctype(value[0])
  458. if isinstance(value, str) and len(value) < 8:
  459. value = bytes(value, "ascii")
  460. if len(value) < 8:
  461. value = value + (8 - len(value)) * b"\0"
  462. return ("8s", value)
  463. raise ValueError(f"Unsupported type {type(value)}")
  464. def get_cpp_type(value: Any) -> str:
  465. """Return equivalent cpp type in string format
  466. :params value:
  467. value to cast into ctype
  468. :returns:
  469. str containing cpp type
  470. """
  471. # used to have compatibility between types
  472. try:
  473. ctype, _ = to_ctype(value)
  474. except ValueError as e:
  475. return f"// Error: {e}"
  476. if ctype == "i":
  477. return "std::int32_t"
  478. if ctype == "l":
  479. return "std::int64_t"
  480. if ctype == "f":
  481. return "float"
  482. if ctype == "d":
  483. return "double"
  484. if ctype == "?":
  485. return "bool"
  486. raise RuntimeError(
  487. f"Should not have reached this part." f"Missing cpp translation for {ctype}"
  488. )
  489. def generate_hparams_struct(
  490. hparams: Dict[str, Any],
  491. struct_name: str,
  492. ) -> str:
  493. """Generate a c++ struct to hold the model hyper-parameters.
  494. :param hparams:
  495. Flattened config of the model.
  496. :param struct_name:
  497. Name of the generated struct.
  498. """
  499. struct = f"struct {struct_name} {{"
  500. fields = [f" {get_cpp_type(value)} {key};" for key, value in hparams.items()]
  501. struct = "\n".join([struct] + fields + ["};\n"])
  502. valid_fields = [
  503. key for key, value in hparams.items() if "Error" not in get_cpp_type(value)
  504. ]
  505. read_struct = f"void read_{struct_name}({struct_name}& out, std::ifstream &fin) {{"
  506. read_fields = [
  507. f" fin.read((char*) &out.{field}, sizeof(out.{field}));"
  508. for field in valid_fields
  509. ]
  510. read_struct = "\n".join([read_struct] + read_fields + ["};\n"])
  511. return "\n".join([struct, read_struct])
  512. if __name__ == "__main__":
  513. import func_argparse
  514. func_argparse.single_main(convert_model)