ggml_convert.py 23 KB

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