Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

ggml_convert.py 25 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...